Instagram
youtube
Facebook
Twitter

Reshape a Pandas DataFrame by Pivoting

A Reshape a Pandas DataFrame by Pivoting?
Code Explanation:
● DataFrame Creation: A sales DataFrame is created.

● Pivoting: .pivot() reshapes it with 'Date' as index and 'Product' as columns.

● Store Result: Pivoted result is stored in pivot_df.

● Output Display: Pivot table is printed.

 

Program:

import pandas as pd

data = pd.DataFrame({'Date': ['Jan', 'Jan', 'Feb'], 'Product': ['A', 'B', 'A'], 'Sales': [100, 150, 200]})

pivot_df = data.pivot(index='Date', columns='Product', values='Sales')

print(pivot_df)