1 回答
TA贡献1777条经验 获得超10个赞
使用GroupBy.std:
df = df.groupby(['timestamp','type'])['value'].std().reset_index()
print (df)
timestamp type value
0 2019-04-01 A NaN
1 2019-04-01 B NaN
2 2019-04-02 A NaN
3 2019-04-02 B 1.414214
如果需要多个指标,可以使用DataFrameGroupBy.describe:
df = df.groupby(['timestamp','type'])['value'].describe()
print (df)
count mean std min 25% 50% 75% max
timestamp type
2019-04-01 A 1.0 3.0 NaN 3.0 3.0 3.0 3.0 3.0
B 1.0 4.0 NaN 4.0 4.0 4.0 4.0 4.0
2019-04-02 A 1.0 5.0 NaN 5.0 5.0 5.0 5.0 5.0
B 2.0 3.0 1.414214 2.0 2.5 3.0 3.5 4.0
有关聚合的更多信息,请参阅熊猫中的聚合。
编辑:如果只需要几个月,请使用Series.dt.month:
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.groupby([df['timestamp'].dt.month.rename('months'),'type'])['value'].describe()
print (df)
count mean std min 25% 50% 75% max
months type
4 A 2.0 4.000000 1.414214 3.0 3.5 4.0 4.5 5.0
B 3.0 3.333333 1.154701 2.0 3.0 4.0 4.0 4.0
如果需要年份和月份,请使用Series.dt.to_period月份:
m = df['timestamp'].dt.to_period('m').rename('months')
df = df.groupby([m,'type'])['value'].describe()
print (df)
count mean std min 25% 50% 75% max
months type
2019-04 A 2.0 4.000000 1.414214 3.0 3.5 4.0 4.5 5.0
B 3.0 3.333333 1.154701 2.0 3.0 4.0 4.0 4.0
添加回答
举报