在Python中使用Pandas添加列和索引以汇总值

2024-09-29 23:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.csv文件,在使用Panda读取它之后,我有这个输出

     Year Month   Brunei Darussalam   ...   Thailand    Viet Nam    Myanmar 
348  2007   Jan                 3813  ...       25863       12555       4887
349  2007   Feb                 3471  ...       22575       11969       3749
350  2007   Mar                 4547  ...       33087       14060       5480
351  2007   Apr                 3265  ...       34500       15553       6838
352  2007   May                 3641  ...       30555       14995       5295
..    ...   ...                  ...  ...         ...         ...        ...
474  2017   Jul                 5625  ...       48620       71153      12619
475  2017   Aug                 4610  ...       40993       51866      10934
476  2017   Sep                 5387  ...       39692       40270       9888
477  2017   Oct                 4202  ...       61448       39013      11616
478  2017   Nov                 5258  ...       39304       36964      11402

我用它来计算总年份内所有国家的总和,以显示前三名

top3_country = new_df.iloc[0:, 2:9].sum(axis=0).sort_values(ascending=False).nlargest(3)

虽然我的输出是这样的

  Indonesia       27572424
  Malaysia        11337420
  Philippines      6548622

我想将列和索引添加到sum值中,就好像它是这样的新数据帧一样

    Countries       Visitors
  0 Indonesia       27572424
  1 Malaysia        11337420
  2 Philippines      6548622

对不起,我才刚刚开始学习熊猫,任何帮助都将不胜感激


Tags: 文件csvyearpandasummyanmarmonthindonesia
2条回答

您可以返回pd.DataFrame,使用reset_indexrename。将代码更改为:

import pandas as pd
top3_country = pd.DataFrame(df.iloc[0:, 2:9].sum(axis=0).sort_values(ascending=False).nlargest(3)
                            ).reset_index(
                                ).rename(columns={'index':'Countries',0:'visitors'})
top3_country

  Countries  visitors
0  Indonesia   27572424
1  Malaysia    11337420
2  Philippines  6548622

对2列DataFrame使用^{},然后从列表中设置新列名称:

top3_country = top3_country.reset_index()
top3_country.columns = ['Countries', 'Visitors']

或者将^{}^{}一起使用:

top3_country = top3_country.rename_axis('Countries').reset_index(name='Visitors')

相关问题 更多 >

    热门问题