函数为通过的pandaDF列制作具有正态曲线的直方图

时间:2018-06-28 12:05:04

标签: python python-3.x pandas matplotlib

我想创建一个使用df和col并返回带有法线曲线和一些标签的直方图的函数。我认为可以使用和定制的东西适合将来的数据(将感谢您提出的一些建议,以使其更具可定制性)。这是为kaggle泰坦尼克号训练集制作的,如果需要,请从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?此功能可自定义吗?不是主要问题-我可以整齐地做诸如均值/标准差之类的事情,添加更多信息吗?

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(

1 个答案:

答案 0 :(得分:1)

您对normpdf的调用是错误的,因为它期望将x值数组作为第一个参数,而不是箱数。但是无论如何,不​​推荐使用mlab.normpdf。

也就是说,我建议使用norm.pdf中的scipy

from scipy.stats import norm

s = np.std(df[col])
m = df[col].mean()
x = np.linspace(m - 3*s, m + 3*s, 51)
y = norm.pdf(x, loc=m)   # additionally there's a `scale` parameter for norming against whatever in y-direction

ax.plot(x, y, '--', label='probability density function')

PS:将nan放到您拥有的熊猫数据框中

df[col].dropna()

即:

n, bins, patches = ax.hist(df[col].dropna(), n_bins, normed=1)