TL; DR
如何编写涉及groupby()
,unstack()
或apply()
等许多操作的长聚合?
示例
假设DataFrame()
n_sales = 1000
个n_events = 10
个不同活动的门票销售,例如
import pandas as pd
import numpy as np
sales = pd.DataFrame({
'Event': np.random.choice(range(n_events), n_sales),
'Time': np.random.rand(n_sales)})
并且您想要绘制在晚上至少售出n = [50, 100]
张票数的事件:
然后我会做
accumulation_of_sales = sales.groupby(['Time', 'Event']).size().unstack().fillna(0).cumsum()
events_with_n_sales = accumulation_of_sales.apply(lambda x: x.value_counts(), axis=1).fillna(0)
events_with_geq_n_sales = events_with_n_sales[events_with_n_sales.columns[::-1]].cumsum(axis=1)
events_with_geq_n_sales[n].plot()
这似乎很难读给我,原则上这些线太长了(见PEP)。所以,
答案 0 :(得分:4)
编写多行pandas查询的一种方法是使用:
accumulation_of_sales = sales.groupby(['Time', 'Event'])\
.size()\
.unstack()\
.fillna(0)\
.cumsum()
我有时更喜欢用括号括起来。
但是,如果你经常在这里做几件事,那就有一种更简单的方法。例如,每当你看到" groupby + unstack"你应该考虑" pivot_table":
sales.pivot_table(columns='Event', index='Time', aggfunc=len, fill_value=0).cumsum()
(这是等效的,更有效,更易读的。)
答案 1 :(得分:2)
除了@Andy的方法。我更喜欢使用括号()来编写多行语句
accumulation_of_sales = (sales.groupby(['Time', 'Event'])
.size()
.unstack()
.fillna(0)
.cumsum())