In [9]:
# Basic Pivot
import pandas as pd
df = pd.DataFrame({
''''Date'''': [''''2024-01-01'''', ''''2024-01-02'''', ''''2024-01-03''''],
''''City'''': [''''New York'''', ''''Los Angeles'''', ''''Chicago''''],
''''Temperature'''': [30, 22, 25]
})
pivot_df = df.pivot(index=''''Date'''', columns=''''City'''', values=''''Temperature'''')
print("Source")
print(df)
print("Pivot")
print(pivot_df)
Source Date City Temperature 0 2024-01-01 New York 30 1 2024-01-02 Los Angeles 22 2 2024-01-03 Chicago 25 Pivot City Chicago Los Angeles New York Date 2024-01-01 NaN NaN 30.0 2024-01-02 NaN 22.0 NaN 2024-01-03 25.0 NaN NaN
In [10]:
# Pivot with MultiIndex
import pandas as pd
df = pd.DataFrame({
''''Date'''': [''''2024-01-01'''', ''''2024-01-01'''', ''''2024-01-02'''', ''''2024-01-02''''],
''''City'''': [''''New York'''', ''''Los Angeles'''', ''''New York'''', ''''Los Angeles''''],
''''Temperature'''': [30, 22, 28, 24]
})
pivot_df = df.pivot(index=''''Date'''', columns=''''City'''', values=''''Temperature'''')
print("Source")
print(df)
print("Pivot")
print(pivot_df)
Source Date City Temperature 0 2024-01-01 New York 30 1 2024-01-01 Los Angeles 22 2 2024-01-02 New York 28 3 2024-01-02 Los Angeles 24 Pivot City Los Angeles New York Date 2024-01-01 22 30 2024-01-02 24 28
In [11]:
# Pivot with Aggregation
import pandas as pd
df = pd.DataFrame({
''''Date'''': [''''2024-01-01'''', ''''2024-01-01'''', ''''2024-01-02'''', ''''2024-01-02''''],
''''City'''': [''''New York'''', ''''Los Angeles'''', ''''New York'''', ''''Los Angeles''''],
''''Temperature'''': [30, 22, 28, 24]
})
pivot_table_df = df.pivot_table(index=''''Date'''', columns=''''City'''', values=''''Temperature'''', aggfunc=''''mean'''')
print("Source")
print(df)
print("Pivot")
print(pivot_table_df)
Source Date City Temperature 0 2024-01-01 New York 30 1 2024-01-01 Los Angeles 22 2 2024-01-02 New York 28 3 2024-01-02 Los Angeles 24 Pivot City Los Angeles New York Date 2024-01-01 22.0 30.0 2024-01-02 24.0 28.0
In [12]:
# Pivot with Multiple Values
import pandas as pd
df = pd.DataFrame({
''''Date'''': [''''2024-01-01'''', ''''2024-01-01'''', ''''2024-01-02'''', ''''2024-01-02''''],
''''City'''': [''''New York'''', ''''Los Angeles'''', ''''New York'''', ''''Los Angeles''''],
''''Temperature'''': [30, 22, 28, 24],
''''Humidity'''': [55, 60, 50, 65]
})
pivot_df = df.pivot(index=''''Date'''', columns=''''City'''', values=[''''Temperature'''', ''''Humidity''''])
print("Source")
print(df)
print("Pivot")
print(pivot_df)
Source Date City Temperature Humidity 0 2024-01-01 New York 30 55 1 2024-01-01 Los Angeles 22 60 2 2024-01-02 New York 28 50 3 2024-01-02 Los Angeles 24 65 Pivot Temperature Humidity City Los Angeles New York Los Angeles New York Date 2024-01-01 22 30 60 55 2024-01-02 24 28 65 50