【发布时间】:2014-10-31 00:05:36
【问题描述】:
这就是我要解释的:
>>> pd.Series([7,20,22,22]).std()
7.2284161474004804
>>> np.std([7,20,22,22])
6.2599920127744575
答案:这是由Bessel's correction、N-1 解释,而不是标准差公式的分母中的N。我希望 Pandas 使用与 numpy 相同的约定。
有一个相关的讨论here,但他们的建议也不起作用。
我有许多不同餐厅的数据。这是我的数据框(想象不止一家餐厅,但效果只复制了一家):
>>> df
restaurant_id price
id
1 10407 7
3 10407 20
6 10407 22
13 10407 22
问题:r.mi.groupby('restaurant_id')['price'].mean() 返回每个餐厅的价格平均值。我想得到标准偏差。但是,r.mi.groupby('restaurant_id')['price'].std() 返回错误值。
如您所见,为简单起见,我只提取了一家包含四项商品的餐厅。我想找到价格的标准差。只是为了确保:
>>> np.mean([7,20,22,22])
17.75
>>> np.std([7,20,22,22])
6.2599920127744575
我们可以得到相同(正确)的值
>>> np.mean(df)
restaurant_id 10407.00
price 17.75
dtype: float64
>>> np.std(df)
restaurant_id 0.000000
price 6.259992
dtype: float64
(当然,忽略平均餐厅 ID。)显然,np.std(df) 不是我拥有多个餐厅的解决方案。所以我使用groupby。
>>> df.groupby('restaurant_id').agg('std')
price
restaurant_id
10407 7.228416
什么?! 7.228416 不是 6.259992。
让我们再试一次。
>>> df.groupby('restaurant_id').std()
同样的事情。
>>> df.groupby('restaurant_id')['price'].std()
同样的事情。
>>> df.groupby('restaurant_id').apply(lambda x: x.std())
同样的事情。
但是,这是可行的:
for id, group in df.groupby('restaurant_id'):
print id, np.std(group['price'])
问题:有没有合适的方法来聚合数据框,所以我会得到一个新的时间序列,其中包含每家餐厅的标准差?
【问题讨论】:
-
pd.Series([7,20,22,22]).std(ddof=0)与np.std的数字相同 -
好的,已解决。我想我必须考虑一下,我要使用哪一个。
标签: python numpy pandas group-by statistics