2

I have a .csv file, after reading it using Panda I have this output

     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

I use this to get me the sum of all countries within the total years to display top 3

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

though my output is this

  Indonesia       27572424
  Malaysia        11337420
  Philippines      6548622

I want to add columns and index into the sum value as if it was a new dataframe like this

    Countries       Visitors
  0 Indonesia       27572424
  1 Malaysia        11337420
  2 Philippines      6548622

Sorry I am just starting to learn learn Panda any help will be gladly appreciated

4

2 Answers 2

0

Use Series.reset_index for 2 columns DataFrame and then set new columns names from list:

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

Or use Series.rename_axis with Series.reset_index:

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

You can return back pd.DataFrame, use reset_index, and rename. Change your code to:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.