TL; DR
如何编写涉及许多操作(如groupby()
,unstack()
或apply()
的长聚合)?
例
假设您有一个DataFrame()
带有n_sales = 1000
个不同活动的门票销售,例如
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_events = 10
张门票的事件数量:
那我会做
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)。所以,
如何最好地执行此特定和类似的操作?
有一些针对初学者的教程/样式指南/ ...吗?也许不是特别针对熊猫,而是类似的语言?
python大神给出的解决方案
编写多行熊猫查询的一种方法是使用:
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()
(这是等效的,效率更高,可读性更好。)