【发布时间】:2018-06-28 12:05:03
【问题描述】:
我想创建一个函数,它接受一个 df 和 col 并返回一个带有正态曲线和一些标签的直方图。我可以使用和定制的东西,因为我认为适合未来的数据(将感谢任何建议,使其更可定制)。这是为 kaggle titanic 训练集制作的,如果需要,请从here 下载。此函数适用于没有 NaN 值的列。列Age 有NaN,我认为这是抛出错误。我尝试使用Error when plotting DataFrame containing NaN with Pandas 0.12.0 and Matplotlib 1.3.1 on Python 3.3.2 忽略NaN,其中一种解决方案建议使用subplot,但这对我不起作用;接受的解决方案是降级 matplotlib(我的版本是 '2.1.2',python 是 3.6.4)。这个pylab histogram get rid of nan 使用了一种有趣的方法,我无法在我的情况下应用。如何删除 NaN ?这个功能可以自定义吗?不是主要问题 - 我可以巧妙地做诸如round mean/std之类的事情,添加更多信息吗?
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mydf = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
def df_col_hist (df,col, n_bins):
fig, ax = plt.subplots()
n, bins, patches = ax.hist(df[col], n_bins, normed=1)
y = mlab.normpdf(bins, df[col].mean(), df[col].std())
ax.plot(bins, y, '--')
ax.set_xlabel (df[col].name)
ax.set_ylabel('Probability density')
ax.set_title(f'Histogram of {df[col].name}: $\mu={df[col].mean()}$, $\sigma={df[col].std()}$')
fig.tight_layout()
plt.show()
df_col_hist (train_data, 'Fare', 100)
#Works Fine, Tidy little histogram.
df_col_hist (train_data, 'Age', 100)
#ValueError: max must be larger than min in range parameter.
..\Anaconda3\lib\site-packages\numpy\core\_methods.py:29: RuntimeWarning: invalid value encountered in reduce
return umr_minimum(a, axis, None, out, keepdims)
..\Anaconda3\lib\site-packages\numpy\core\_methods.py:26: RuntimeWarning: invalid value encountered in reduce
return umr_maximum(a, axis, None, out, keepdims)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-75-c81b76c1f28e> in <module>()
----> 1 df_col_hist (train_data, 'Age', 100)
<ipython-input-70-1cf1645db595> in df_col_hist(df, col, n_bins)
2
3 fig, ax = plt.subplots()
----> 4 n, bins, patches = ax.hist(df[col], n_bins, normed=1)
5
6 y = mlab.normpdf(bins, df[col].mean(), df[col].std())
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1715 warnings.warn(msg % (label_namer, func.__name__),
1716 RuntimeWarning, stacklevel=2)
-> 1717 return func(ax, *args, **kwargs)
1718 pre_doc = inner.__doc__
1719 if pre_doc is None:
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
6163 # this will automatically overwrite bins,
6164 # so that each histogram uses the same bins
-> 6165 m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
6166 m = m.astype(float) # causes problems later if it's an int
6167 if mlast is None:
~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in histogram(a, bins, range, normed, weights, density)
665 if first_edge > last_edge:
666 raise ValueError(
--> 667 'max must be larger than min in range parameter.')
668 if not np.all(np.isfinite([first_edge, last_edge])):
669 raise ValueError(
【问题讨论】:
标签: python python-3.x pandas matplotlib