python - 聚合和透视数据框的更快替代方案?
问题描述
我有一个看起来像这样的人口数据数据框,其中每一行都是在特定日期拍摄的县人口
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')
事实证明,这非常缓慢,因为数百年来每年都有几个条目。我能做些什么来让这个运行更快
解决方案
让我们尝试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
推荐阅读
- java - 为什么在表中插入记录后休眠更新
- sql - 在拆分表单视图中,如何从子表单中获取准确的总计,目前需要在总计正确之前选择每条记录
- cassandra - Cassandra 3.11.4 中服务器端的慢速查询记录器 Cassandra
- java - Calender.set(Calender.Month, ?) 如何工作?
- java - SnakeYaml 未序列化私有或受保护字段
- google-oauth - 应该在哪里创建 Google 服务帐户?应用程序的域?还是在每个客户的域中?
- java - 无法在图像上显示图像
- docker - 在另一个容器的本地主机上发布端口
- xcode10.1 - Xcode 10.1 在故事板文件的版本编辑器中突出显示一行(或多行)
- unix - 通过 SOCKS 路由所有控制台流量