首页 > 解决方案 > 聚合和透视数据框的更快替代方案?

问题描述

我有一个看起来像这样的人口数据数据框,其中每一行都是在特定日期拍摄的县人口

County Date     Population
Alba   1900-1-1   1094
Alba   1900-2-1   1107
Alba   1900-3-1   1120
Belfor 1900-1-1   9756
Belfor 1900-3-1   9976
...

我想得到一个数据框,其中索引是年份,列是县名,值是给定年份的平均人口。

这就是我的代码目前的样子

#year
df['Year'] = pd.DatetimeIndex(df['date']).year.fillna(0).astype(int)

##create aggregation on year, county of population
new_df =  df.groupby(['Year','County']).mean()
#turn county into column
new_df.reset_index(level=1, inplace=True)
##pivot dataframe
new_df.pivot(columns='Country',values='Population')

事实证明,这非常缓慢,因为数百年来每年都有几个条目。我能做些什么来让这个运行更快

标签: pythonpandasdataframepivot-tableaggregate

解决方案


让我们尝试crosstab创建一个交叉表:

df['Date'] = pd.to_datetime(df['Date'])
pd.crosstab(df['Date'].dt.year, df['County'], df['Population'], aggfunc='mean')

或者,您可以使用pivot_table

df.pivot_table(index=df['Date'].dt.year, columns='County', values='Population', aggfunc='mean')

结果:

County  Alba  Belfor
Date                
1900    1107    9866

推荐阅读