Home > Backend Development > Python Tutorial > How Can I Effectively Pivot a Pandas DataFrame?

How Can I Effectively Pivot a Pandas DataFrame?

Barbara Streisand
Release: 2024-12-27 15:43:11
Original
305 people have browsed it

How Can I Effectively Pivot a Pandas DataFrame?

How can I pivot a dataframe?

A pivot is a transformation that takes a dataframe with columns representing categories and rows representing values, and reorients it so that the categories are in the rows, the values are in the columns, and the index is set to the original row values.

Basic syntax:

df.pivot(index=<row_labels>, columns=<col_labels>, values=<value_cols>)
Copy after login

Examples:

  • Pivot on a single column:
df.pivot(index='row', columns='col', values='val')
Copy after login
  • Pivot on multiple columns:
df.pivot(index=['row', 'item'], columns='col', values='val')
Copy after login
  • Pivot on multiple values:
df.pivot(index='row', columns='col', values=['val0', 'val1'])
Copy after login
  • Pivot with custom aggregation functions:
df.pivot(index='row', columns='col', values='val', aggfunc='mean')
Copy after login
  • Handling duplicate keys:

By default, if there are duplicate keys in the row or column labels, an error will be raised. Alternatively, you can use:

df.pivot_table(index='row', columns='col', values='val', fill_value=0)
Copy after login
  • Other methods for pivoting:
  • groupby unstack:

    df.groupby('row', 'col')['val'].mean().unstack(fill_value=0)
    Copy after login
  • pd.DataFrame.set_index: Use set_index to set the row and column axes and then unstack to pivot.
  • pd.crosstab: Specifically designed for creating crosstabulations or pivot tables.

Advanced Pivoting Techniques:

  • Cross-tabulation (frequency counting):
pd.crosstab(index=df['row'], columns=df['col'], values=df['val'], aggfunc='count')
Copy after login
  • Multiple aggregation functions:
df.pivot_table(index='row', columns='col', values='val', aggfunc=['mean', 'sum'])
Copy after login
  • Subdividing by multiple columns:
df.pivot_table(index='row', columns=['item', 'col'], values='val', fill_value=0, aggfunc='mean')
Copy after login

The above is the detailed content of How Can I Effectively Pivot a Pandas DataFrame?. 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