在Python中使用Panda添加列和索引来求和值



我有一个。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

我用它来获得所有国家在总年份内显示前3名的总和

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

使用Series.reset_index作为2列DataFrame,然后从list中设置新的列名:

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

或使用Series.rename_axisSeries.reset_index:

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

您可以返回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

最新更新