问题
when plotting Pandas dataframe using a histogram,
sample dataframe data
distance
0 5.680195
2 0.000000
3 7.974658
4 2.461387
5 9.703089
code I use to plot
import matplotlib.pyplot as plt
plt.hist(df['distance'].values)
plt.show()
I have this error
"ValueError: range parameter must be finite."
my attempt
df['Round_Distance'] = df['distance'].round(1)
0 5.7
2 0.0
3 8.0
4 2.5
5 9.7
plot again, new error
plt.hist(df['Round_Distance'].values)
plt.show()
ValueError: max must be larger than min in range parameter.
weird thing is, the work around i use is below, i don't have to ROUND
df['distance'].hist(bins=[0,25,50,75,100,125,150,175], color='g')
回答1:
Sounds like you have some NaNs
or inf
in your actual data. You can select only those values that are finite like this:
import numpy as np
df[np.isfinite(df['distance'])]
So your plot can be obtained like:
plt.hist(df[np.isfinite(df['distance'])].values)
回答2:
Just to add to sacul's answer, you can check if you have NaNs
or inf
on any of your columns using this:
For NaNs
:
df.isnull().sum()
For inf
:
df.max()
Hope it helps !
回答3:
NaN cause the issue, i don't need to round it, just drop the NaN, then it works
plt.hist(df['distance'].dropna().values)
plt.show()
来源:https://stackoverflow.com/questions/51642846/python-histogram-valueerror-range-parameter-must-be-finite