Pandas: Pivot a DataFrame

19 August 2020

Code

# Import library
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'day': ['Sunday', 'Sunday', 'Sunday', 'Sunday', 'Monday', 'Monday', 'Monday', 'Monday'],
    'store': ['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D'],
    'number_of_customers': [104, 200, 120, 123, 55, 69, 30, 76]
})
print('DataFrame to be pivoted: \n', df)

Intermediate output:

DataFrame to be pivoted: 
       day store  number_of_customers
0  Sunday     A                  104
1  Sunday     B                  200
2  Sunday     C                  120
3  Sunday     D                  123
4  Monday     A                   55
5  Monday     B                   69
6  Monday     C                   30
7  Monday     D                   76

Further code:

# Pivot the DataFrame
df2 = df.pivot(index='day', columns='store', values='number_of_customers')

# Output
print(df2)

Output

store     A    B    C    D
day                       
Monday   55   69   30   76
Sunday  104  200  120  123






Any errors in code above?
Please send a message.