Home >Backend Development >Python Tutorial >How can I transpose a DataFrame to pivot its rows and columns in Pandas?

How can I transpose a DataFrame to pivot its rows and columns in Pandas?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 14:45:031113browse

How can I transpose a DataFrame to pivot its rows and columns in Pandas?

Transposing DataFrames for Pivoting

Pivoting a DataFrame refers to transposing its rows and columns to achieve a different representation of the data. In Pandas, the pivot method can be employed for this purpose.

Consider the following DataFrame:

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

To pivot this DataFrame to have indicator values as new columns:

out = df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value')
print(out)

This results in:

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

To revert to an unpivoted format:

print(out.rename_axis(columns=None).reset_index())

This produces:

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

Using .pivot_table

If duplicate label combinations exist, pivot_table can be utilized. It calculates the mean by default:

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

Resulting in:

  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

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

The above is the detailed content of How can I transpose a DataFrame to pivot its rows and columns in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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