Home > Backend Development > Python Tutorial > How Can I Pivot a Pandas Dataframe to Reshape Data by Specific Columns?

How Can I Pivot a Pandas Dataframe to Reshape Data by Specific Columns?

Mary-Kate Olsen
Release: 2024-11-23 01:25:16
Original
220 people have browsed it

How Can I Pivot a Pandas Dataframe to Reshape Data by Specific Columns?

Transposing Pandas Dataframes for Data Pivoting

In data analysis, transposing a dataframe is crucial for organizing data into a more suitable format. One common use case is pivoting a dataframe based on specific column values.

For a CSV table containing data as follows:

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
Copy after login

you can pivot the dataframe to obtain this format:

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

To achieve this transformation, you can utilize the .pivot method as follows:

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

For data with duplicate label combinations, you can employ the .pivot_table method, which applies the mean calculation by default:

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

By utilizing the .rename_axis and .reset_index methods, you can restore the dataframe to a flat table format.

Refer to the Pandas user guide for in-depth documentation on reshaping and pivot tables.

The above is the detailed content of How Can I Pivot a Pandas Dataframe to Reshape Data by Specific Columns?. 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