熊猫中的数据透视表

时间:2020-06-22 09:15:37

标签: python pandas

我想为 Count_Orders Count_Sessions 创建数据透视表。但是,使用当前代码,一旦我尝试添加** Count_Sessions“,我就只能对 Count_Orders 进行计算,但会出现以下错误:

SyntaxError: positional argument follows keyword argument

主表

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

所需的输出表

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

我当前的代码:

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

1 个答案:

答案 0 :(得分:1)

这是一个解决方案:

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) 

输出为:

enter image description here