首页 > 解决方案 > 使用 Pandas 汇总数据

问题描述

我正在尝试过滤和汇总 Python 中的数据表。我正在努力选择年份(以“Y”开头的列)并计算该年每个国家/地区的平均值。下面是我尝试的最后一段代码。我很感激任何反馈:

我的 CSV 位于以下链接:

https://docs.google.com/spreadsheets/d/1e6R9Tse_Zt3AcY0pPAObdX5XVYKt6ZufHMG7nWLABMQ/edit?usp=sharing

areac= Temp_Change.columns.get_loc('Area')
monthc= Temp_Change.columns.get_loc[8:65]
df = Temp_Change.iloc[areac:monthc]

标签: pythonpandasfilter

解决方案


请看看这是否解决了您的问题。

dfg = Temp_Change.groupby('Area').mean().loc[:, 'Y1961':]

在此处输入图像描述

如果要堆叠这些year列。

dfs = dfg.stack().reset_index()
dfs.columns = ['Area', 'Year', 'Avg_Temp']
dfs['Year'] = dfs['Year'].apply(lambda x: int(x[-4:]))

在此处输入图像描述


推荐阅读