close

How to pivot a dataframe in Pandas?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to pivot a dataframe in Pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to pivot a dataframe in Pandas?

  1. How to pivot a dataframe in Pandas?

    You can use pivot_table:
    pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()

  2. pivot a dataframe in Pandas

    You can use pivot_table:
    pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()

Method 1

You can use pivot_table:

pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()

this outputs:

 Indicator  Country     Year    1   2   3   4   5
 0          Angola      2005    6   13  10  11  5
 1          Angola      2006    3   2   7   3   6

Method 2

This is a guess: it’s not a “.csv” file, but a Pandas DataFrame imported from a ‘.csv’.

To pivot this table you want three arguments in your Pandas “pivot”. e.g., if df is your dataframe:

table = df.pivot(index='Country',columns='Year',values='Value')  
print (table)

This should should give the desired output.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read