Python Func为通过的pandaDF列生成具有法线曲线的直方图
我想创建一个函数,它接受df和col并返回一个带有法线曲线和一些标签的直方图。一些我认为适合未来数据使用和定制的东西(非常感谢任何建议,以使其更加可定制)。这是为卡格尔泰坦尼克号训练集制作的,如果需要,请从下载。对于没有Python Func为通过的pandaDF列生成具有法线曲线的直方图,python,python-3.x,pandas,matplotlib,Python,Python 3.x,Pandas,Matplotlib,我想创建一个函数,它接受df和col并返回一个带有法线曲线和一些标签的直方图。一些我认为适合未来数据使用和定制的东西(非常感谢任何建议,以使其更加可定制)。这是为卡格尔泰坦尼克号训练集制作的,如果需要,请从下载。对于没有NaN值的列,此函数工作正常。列Age有NaN,我认为这就是抛出错误的原因。我试图忽略NaN使用其中一个解决方案建议使用的子地块,但它对我不起作用;公认的解决方案是降级matplotlib(我的版本是'2.1.2',python是3.6.4)。这使用了一种有趣的方法,但我无法将其
NaN
值的列,此函数工作正常。列Age
有NaN
,我认为这就是抛出错误的原因。我试图忽略NaN
使用其中一个解决方案建议使用的子地块
,但它对我不起作用;公认的解决方案是降级matplotlib
(我的版本是'2.1.2',python是3.6.4)。这使用了一种有趣的方法,但我无法将其应用到我的案例中。如何删除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(
将numpy导入为np
作为pd进口熊猫
将matplotlib.mlab导入为mlab
将matplotlib.pyplot作为plt导入
mydf=pd.DataFrame(np.random.randint(0100,size=(100,4)),columns=list('ABCD'))
def df_col_hist(df、col、n_bins):
图,ax=plt.子批次()
n、 存储单元,补丁=ax.hist(df[col],n_存储单元,normed=1)
y=mlab.normpdf(容器,df[col].mean(),df[col].std())
ax.绘图(箱,y,'-')
ax.set\u xlabel(df[col].name)
ax.set_ylabel(‘概率密度’)
ax.set_title({df[col].name}:$\mu={df[col].mean()}$,$\sigma={df[col].std()}$的直方图)
图1紧_布局图()
plt.show()
df_col_hist(列车数据,'票价',100)
#做工精细、整洁的小柱状图。
df_col_hist(列车数据,'Age',100)
#ValueError:范围参数中的最大值必须大于最小值。
..\Anaconda3\lib\site packages\numpy\core\\u methods.py:29:RuntimeWarning:reduce中遇到无效值
返回umr_最小值(a、轴、无、输出、保持)
..\Anaconda3\lib\site packages\numpy\core\\u methods.py:26:RuntimeWarning:reduce中遇到无效值
返回umr_最大值(a、轴、无、输出、保持)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
---->1个df_col_hist(列车数据,'Age',100)
在df_col_hist中(df,col,n_bin)
2.
3图,ax=plt.子批次()
---->4个n,单元,补丁=ax.hist(df[col],n_单元,normed=1)
5.
6 y=mlab.normpdf(料仓,df[col].mean(),df[col].std())
内部的~\Anaconda3\lib\site packages\matplotlib\\uuuu init\uuuuuu.py(ax、*args、**kwargs)
1715警告。警告(消息%(标签名称,功能名称),
1716运行时警告,堆栈级别=2)
->1717返回函数(ax,*args,**kwargs)
1718预付款单=内部付款单__
1719如果pre_doc为无:
hist中的~\Anaconda3\lib\site packages\matplotlib\axes\\u axes.py(***解析参数失败***)
6163#这将自动覆盖垃圾箱,
6164#因此每个直方图使用相同的箱子
->6165米,料仓=np。直方图(x[i],料仓,权重=w[i],**hist_kwargs)
6166 m=m.astype(float)#如果是int,则稍后会导致问题
6167如果mlast为无:
直方图中的~\Anaconda3\lib\site packages\numpy\lib\function\u base.py(a、箱子、范围、赋范、权重、密度)
665如果第一条边>最后一条边:
666提升值错误(
-->667“范围参数中的最大值必须大于最小值”。)
668如果不是np.all(np.isfinite([第一条边,最后一条边]):
669提升值错误(
您对normpdf
的调用是错误的,因为它需要一个x值数组作为第一个参数,而不是箱子的数量。但是无论如何,mlab.normpdf是不推荐的
也就是说,我建议使用norm.pdffromscipy
:
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()
即:
Freeeeezzzee!!!删除na,使用可用值,制作直方图!谢谢。。
n, bins, patches = ax.hist(df[col].dropna(), n_bins, normed=1)