我想用3年的时间来计算平均值。 我的数据是这样的:
import pandas as pd
import numpy as np
N=120
data = {'p1': np.random.randint(50,100,N),
'p2': np.random.randint(0,100,N),
'p3': np.random.randint(10,70,N)
}
df = (pd.DataFrame(data, index=pd.bdate_range(start='20100101', periods=N, freq='BM'))
.stack()
.reset_index()
.rename(columns={'level_0': 'date', 'level_1': 'type', 0: 'price'})
.sort_values('date')
)
我尝试过:
(df.sort_values('date')
.groupby(['type',
''.join([(df.date.dt.year-3), '-', (df.date.dt.year)]) #3 years time span
]
)
['price']
.apply(lambda x: x.mean())
)
但收到错误消息:
TypeError: sequence item 0: expected str instance, Series found
我想按类型/时间段分别按2010-2013年,2011-2014年,2012-2015年的类型/时间计算价格平均值(以及其他统计信息)...
标签很重要,因为我可以使用:
(df.sort_values('date')
.groupby(['type', df.date.dt.year//3]) #3 years time span
['price']
.apply(lambda x: x.mean())
)
有什么想法吗?
答案 0 :(得分:1)
我认为我找到了自己的问题的答案(可能对其他人感兴趣):
(df.sort_values('date')
.groupby(['type', (df.date.dt.year-3).astype(str).str.cat((df.date.dt.year).astype(str), sep='-')
]
)
['price']
.apply(lambda x: x.mean())
)