user12625679
user12625679

Reputation: 696

Pivot table in Pandas

I would like to create a pivot table for Count_Orders as well as Count_Sessions. However, with the current code I can only do the calculation for Count_Orders once I am trying to add **Count_Sessions" I get the following error:

SyntaxError: positional argument follows keyword argument

Main table

Month      Country  Count_Orders Count_Sessions
2019-01    UK       100           40
2019-01    US       230           60

Desired Output table

Month      US_Orders  US_Sessions  UK_Orders US_Sessions Share_Orders Share_Sessions
2019-01    100        230          40        60          0.43          0.66

My current code:

df_pivot = pd.pivot_table(appended_df, index=['Month'], columns='Country', values='Count_Orders') #Pivoting on required columns
df_flattened = pd.DataFrame(df_pivot.to_records()) #Flatten the pivot table to get a datafrmae
df_flattened['Share'] = df_flattened['UK']/df_flattened['US'] #Creating the ratio column

Upvotes: 0

Views: 113

Answers (1)

Roy2012
Roy2012

Reputation: 12523

Here's a solution:

res = pd.pivot_table(df, index="Month", columns=["Country"])

res.columns = [c[0] + "_" + c[1] for c in res.columns]
res[["orders_ratio", "sessions_ratio"]] = res.iloc[:, [0,2]].divide(res.iloc[:, [1,3]].values) 

The output is:

enter image description here

Upvotes: 1

Related Questions