import pandas as pd
data = {
'Date': ['1/12/2002', '1/12/2002', '1/12/2002', '1/12/2002', '1/01/2003', '1/01/2003', '1/01/2003', '1/01/2003', '1/01/2003'],
'id': [1, 1, 1, 2, 1, 1, 2, 2, 2],
'class': ['L', 'H', 'L', 'L', 'L', 'H', 'H', 'L', 'L'],
'amount': [5, 6, 7, 3, 2, 8, 7, 9, 1]
}
df = pd.DataFrame(data)
# Pivot the DataFrame
pivot_df = df.pivot_table(index=['Date', 'id'], columns='class', values='amount', aggfunc='sum', fill_value=0)
pivot_df.columns = [f'{col}_class' for col in pivot_df.columns]
# Reset index to get Date and id back as columns
pivot_df = pivot_df.reset_index()
print(pivot_df)
Output:
Date id H_class L_class
0 1/01/2003 1 8 2
1 1/01/2003 2 7 10
2 1/12/2002 1 6 12
3 1/12/2002 2 0 3