Home > Backend Development > Python Tutorial > How to Pivot a Dataframe in Pandas?

How to Pivot a Dataframe in Pandas?

Mary-Kate Olsen
Release: 2024-11-12 19:27:02
Original
771 people have browsed it

How to Pivot a Dataframe in Pandas?

Pivot a Dataframe in Pandas

To pivot a dataframe in Pandas, you can use the .pivot method. This method takes the specified values as columns and rearranges the dataframe accordingly.

Suppose you have a dataframe with columns Indicator, Country, Year, and Value. To transpose the table so that the values in the Indicator column become the new columns, use the following code:

out = df.pivot(index=['Country', 'Year'], columns='Indicator', values='Value')
print(out)
Copy after login

The resulting output will be:

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

To convert the pivoted dataframe back to a flat table, you can use .rename_axis to remove the Indicator column and .reset_index to revert Country and Year to normal columns:

print(out.rename_axis(columns=None).reset_index())
Copy after login

The output will be:

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

If your data has duplicate combinations of labels (e.g., Country, Year, Indicator), you can use .pivot_table instead. By default, it takes the mean of repeated values:

out = df.pivot_table(
    index=['Country', 'Year'],
    columns='Indicator',
    values='Value')
print(out.rename_axis(columns=None).reset_index())
Copy after login

The output will be:

  Country  Year    1     2     3     4    5
0  Angola  2005  6.0  13.0  10.0  11.0  5.0
1  Angola  2006  3.0   2.0   7.0   3.0  6.0
Copy after login

For more information on reshaping and pivot tables in Pandas, refer to the user guide.

The above is the detailed content of How to Pivot a Dataframe in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template