Home >Backend Development >Python Tutorial >How to Pivot a Pandas DataFrame: A Comprehensive Guide to Reshaping Data?
Several methods to pivot a DataFrame:
Long format:
Wide format:
Use pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index='row', columns='col', aggfunc='mean')
Use fill_value argument in pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index='row', columns='col', fill_value=0, aggfunc='mean')
Use a different aggfunc argument in pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index='row', columns='col', fill_value=0, aggfunc='sum')
Provide a list of callables to the aggfunc argument in pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index='row', columns='col', fill_value=0, aggfunc=[np.size, np.mean])
Pass multiple column names as a list to values in pd.DataFrame.pivot_table:
df.pivot_table(values=['val0', 'val1'], index='row', columns='col', fill_value=0, aggfunc='mean')
Pass multiple column names as a list to index or columns in pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index=['row', 'item'], columns='col', fill_value=0, aggfunc='mean')
Can subdivide by multiple columns in index and columns using pd.DataFrame.pivot_table:
df.pivot_table(values='val0', index=['key', 'row'], columns=['item', 'col'], fill_value=0, aggfunc='mean')
Use pd.crosstab:
df.pivot_table(values='val0', index='row', columns='col', aggfunc='mean')
df.pivot_table(values='val0', index='row', columns='col', fill_value=0, aggfunc='mean')
Join the multi-part index as a single string:
df.pivot_table(values='val0', index='row', columns='col', fill_value=0, aggfunc='sum')
The above is the detailed content of How to Pivot a Pandas DataFrame: A Comprehensive Guide to Reshaping Data?. For more information, please follow other related articles on the PHP Chinese website!