![](/img/trans.png)
[英]pandas dataframe resample aggregate function use multiple columns with a customized function?
[英]resample and aggregate using *multiple* *named* aggregation functions on *multiple* columns
我有一個像
import pandas as pd
import numpy as np
range = pd.date_range('2015-01-01', '2015-01-5', freq='15min')
df = pd.DataFrame(index = range)
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
df['otherF'] = np.random.randint(low=2, high=42, size=len(df.index))
我可以輕松地重新采樣並將內置函數應用為sum() :
df['speed'].resample('1D').sum()
Out[121]:
2015-01-01 2865
2015-01-02 2923
2015-01-03 2947
2015-01-04 2751
我還可以應用返回多個值的自定義函數:
def mu_cis(x):
x_=x[~np.isnan(x)]
CI=np.std(x_)/np.sqrt(x.shape)
return np.mean(x_),np.mean(x_)-CI,np.mean(x_)+CI,len(x_)
df['speed'].resample('1D').agg(mu_cis)
Out[122]:
2015-01-01 (29.84375, [28.1098628611], [31.5776371389], 96)
2015-01-02 (30.4479166667, [28.7806726396], [32.115160693...
2015-01-03 (30.6979166667, [29.0182072972], [32.377626036...
2015-01-04 (28.65625, [26.965228204], [30.347271796], 96)
正如我在這里讀到的,我什至可以使用一個名稱來實現多個值, pandas 應用函數將多個值返回到pandas 數據幀中的行
def myfunc1(x):
x_=x[~np.isnan(x)]
CI=np.std(x_)/np.sqrt(x.shape)
e=np.mean(x_)
f=np.mean(x_)+CI
g=np.mean(x_)-CI
return pd.Series([e,f,g], index=['MU', 'MU+', 'MU-'])
df['speed'].resample('1D').agg(myfunc1)
這使
Out[124]:
2015-01-01 MU 29.8438
MU+ [31.5776371389]
MU- [28.1098628611]
2015-01-02 MU 30.4479
MU+ [32.1151606937]
MU- [28.7806726396]
2015-01-03 MU 30.6979
MU+ [32.3776260361]
MU- [29.0182072972]
2015-01-04 MU 28.6562
MU+ [30.347271796]
MU- [26.965228204]
但是,當我嘗試將其應用於所有原始列時,我只會得到NaN
:
df.resample('1D').agg(myfunc1)
Out[127]:
speed otherF
2015-01-01 NaN NaN
2015-01-02 NaN NaN
2015-01-03 NaN NaN
2015-01-04 NaN NaN
2015-01-05 NaN NaN
結果不會使用agg
更改或在resample()
之后apply
。
這樣做的正確方法是什么?
問題出在myfunc1
。 它嘗試返回pd.Series
,而您有pd.DataFrame
。 以下似乎工作得很好。
def myfunc1(x):
x_=x[~np.isnan(x)]
CI=np.std(x_)/np.sqrt(x.shape)
e=np.mean(x_)
f=np.mean(x_)+CI
g=np.mean(x_)-CI
try:
return pd.DataFrame([e,f,g], index=['MU', 'MU+', 'MU-'], columns = x.columns)
except AttributeError: #will still raise errors of other nature
return pd.Series([e,f,g], index=['MU', 'MU+', 'MU-'])
或者:
def myfunc1(x):
x_=x[~np.isnan(x)]
CI=np.std(x_)/np.sqrt(x.shape)
e=np.mean(x_)
f=np.mean(x_)+CI
g=np.mean(x_)-CI
if x.ndim > 1: #Equivalent to if len(x.shape) > 1
return pd.DataFrame([e,f,g], index=['MU', 'MU+', 'MU-'], columns = x.columns)
return pd.Series([e,f,g], index=['MU', 'MU+', 'MU-'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.