如何解决聚合和旋转数据框的更快替代方法?
我有一个人口数据的数据框,看起来像这样,其中每一行都是在特定日期获取的一个县的人口
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')
事实证明,这非常缓慢,因为数百年来每年都有多次输入。我该怎么办才能使运行速度更快
解决方法
让我们尝试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
结果:
<ScrollView
contentContainerStyle={{
flexGrow: 1,justifyContent: 'flex-end',}}>
</ScrollView>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。