How to resolve Python Error: "The first argument of bincount must be non-negative"

matplotlib
python

#1

Hi,

I’m trying to create a histogram in python after taking a log transformation using the following code:

coltr = np.log(col)
skew = coltr.skew()
kurt = coltr.kurt()
title = "Histogram | Skew = %f | Kurt = %f"%(np.round(skew,2),np.round(kurt,2))
plt.figure()
plt.hist(coltr, bins=20)  
plt.ylabel("Frequency")
plt.xlabel(col.name)
plt.title(title)
plt.show(block=False)

Here “col” is a pandas series object which has to be transformed and plotted. This code results in an error:
ValueError: The first argument of bincount must be non-negative

I’m unable to figure out a solution. How can the bincount be negative?

Thanks,
Aarshay


#2

@Aarshay,

It may possible that variable has value as zero, check it. If yes, apply log transformation as:

coltr = np.log(col+1)

Regards,
Sunil


#3

Thanks @Sunil!

This was exactly the problem. I had some zeros in input data and taking log was returning -inf.

Using np.log(x+1) solved the issue.

Cheers,
Aarshay


#4