【发布时间】:2014-08-08 19:40:02
【问题描述】:
此问题是对my earlier one 的扩展。我有一个熊猫数据框:
import pandas as pd
codes = ["one","two","three"];
colours = ["black", "white"];
textures = ["soft", "hard"];
N= 100 # length of the dataframe
df = pd.DataFrame({ 'id' : range(1,N+1),
'weeks_elapsed' : [random.choice(range(1,25)) for i in range(1,N+1)],
'code' : [random.choice(codes) for i in range(1,N+1)],
'colour': [random.choice(colours) for i in range(1,N+1)],
'texture': [random.choice(textures) for i in range(1,N+1)],
'size': [random.randint(1,100) for i in range(1,N+1)],
'scaled_size': [random.randint(100,1000) for i in range(1,N+1)]
}, columns= ['id', 'weeks_elapsed', 'code','colour', 'texture', 'size', 'scaled_size'])
我将它按colour 和code 分组,并得到一些关于size 和scaled_size 的统计数据,如下所示:
grouped = df.groupby(['code', 'colour']).agg( {'size': [np.sum, np.average, np.size, pd.Series.idxmax],'scaled_size': [np.sum, np.average, np.size, pd.Series.idxmax]}).reset_index()
现在,我要做的是针对不同的weeks_elapsed 间隔对df 多次运行上述计算。 下面是一个蛮力解决方案,有没有更简洁和更快的方法来运行它?另外,我如何在单个数据帧中连接不同时间间隔的结果?
cut_offs= [4,12]
grouped = {c:{} for c in cut_offs}
for c in cut_offs:
grouped[c] =df.ix[df.weeks_elapsed <= c ].groupby(['code', 'colour']).agg(
{'size': [np.sum, np.average, np.size,pd.Series.idxmax],
'scaled_size': [np.sum, np.average, np.size, pd.Series.idxmax]
}).reset_index()
我对 np.avg 和 np.size 的不同 weeks_elapsed 间隔特别感兴趣。
【问题讨论】:
-
你能更正你的初始df代码吗? 'weeks_elapsed' 与 'w_elapsed' 在列中,'adjust_size' 与 'scaled_size' 相同
-
抱歉,现在更正了。
标签: python pandas group-by conditional-statements dataframe