私はパンダのデータフレームを持っていますdf
:
>>> df
net_inventory sales yr temp_stk_id
STK_ID RPT_Date
34_STK43 20080331 282.1603 359.4644 2008 34_STK43
20080630 297.4760 716.7633 2008 34_STK43
20080930 283.6312 1105.6332 2008 34_STK43
20081231 296.9090 1380.4886 2008 34_STK43
20090331 276.2348 363.3449 2009 34_STK43
20090630 288.0186 753.6347 2009 34_STK43
20090930 287.0811 1173.3760 2009 34_STK43
>>> df.dtypes
net_inventory float64
sales float64
yr object
temp_stk_id object
次に、「net_inventory」列と「sales」列、groupby に対して「expanding_mean()」を実行します ['temp_stk_id','yr']
。
>>> df.groupby(['temp_stk_id','yr']).apply(lambda x: pd.expanding_mean(x))
以下のエラーが発生します。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python\Lib\site-packages\pandas\core\groupby.py", line 322, in apply
return self._python_apply_general(f)
File "D:\Python\Lib\site-packages\pandas\core\groupby.py", line 325, in _python_apply_general
keys, values, mutated = self.grouper.apply(f, self.obj, self.axis)
File "D:\Python\Lib\site-packages\pandas\core\groupby.py", line 596, in apply
res = f(group)
File "D:\Python\Lib\site-packages\pandas\core\groupby.py", line 321, in <lambda>
f = lambda g: func(g, *args, **kwargs)
File "<stdin>", line 1, in <lambda>
File "D:\Python\Lib\site-packages\pandas\stats\moments.py", line 697, in f
time_rule=time_rule, **kwargs)
File "D:\Python\Lib\site-packages\pandas\stats\moments.py", line 281, in _rolling_moment
return_hook, values = _process_data_structure(arg)
File "D:\Python\Lib\site-packages\pandas\stats\moments.py", line 326, in _process_data_structure
values = values.astype(float)
ValueError: invalid literal for float(): 34_STK43
オブジェクト型temp_stk_id
と 'yr' 列に対して expand_mean() が機能しないためだと思うので、次のようにします。
df.groupby(['temp_stk_id','yr']).apply(lambda x: pd.expanding_mean(x) for all columns except [`temp_stk_id`, 'yr'])
また
df.groupby(['temp_stk_id','yr']).apply(lambda x: pd.expanding_mean(x) for specified columns)
どうやってするか ?