简体   繁体   中英

Pandas pivot table, sort values

I am trying to create a pivot table in Pandas.

df_pivot = df_final.groupby('bm').apply(lambda sub: sub.pivot_table(
    index=['Utm_campaign', 'Time'],
    values=['Cost', 'Install', 'Show', 'Link_cliks', 'Reg', 'Ftd'],
    aggfunc=np.sum,
    margins=True,
    margins_name='Total'
))

# Calculation
df_pivot = df_pivot.assign(Instal_cost = df_pivot.Cost/df_pivot.Install)
df_pivot = df_pivot.assign(Reg_cost = df_pivot.Cost/df_pivot.Reg)
df_pivot = df_pivot.assign(FTD_cost = df_pivot.Cost/df_pivot.Ftd)
df_pivot = df_pivot.assign(CTR = df_pivot.Link_cliks/df_pivot.Show*100)

# Replace Inf
df_pivot.replace([np.inf, -np.inf, np.nan], 0, inplace=True)
df_pivot = df_pivot.drop(['Link_cliks', 'Show'], axis=1)

df_pivot = df_pivot.sort_values(by = ["bm", 'Utm_campaign'], axis = 0, ascending=[True, False])

I've attached an image from Excel as it is easier to see in tabular format what I am trying to achieve.

链接到图片

I tried using.sort_values() but I couldn't sort ' Cost '.

Thanks in advance


df_pivot:

bm Utm_campaign Time Cost Ftd Install Reg Instal_cost Reg_ cost FTD_cost CTR
name49438 Total 2,43 0 0 0 0 0 0 0
OPD_DE_SL_name49438 11:00 2,43 0 0 0 0 0 0 0
name54908 Total 8,5 0 2 1 4,25 8,5 0 1,02
OPD_DE_SL_name54908 10:00 8,5 0 2 0 4,25 0 0 1,02
11:00 0 0 0 1 0 0 0 0
name56281 Total 17,76 0 4 3 4,44 5,92 0 0,63
OPD_DE_name56281 11:00 17,76 0 4 3 4,44 5,92 0 0,63
name57749 Total 0,01 0 0 0 0 0 0 0
OPD_DE_SL_name57749 10:00 0,01 0 0 0 0 0 0 0
11:00 0 0 0 0 0 0 0 0

Try:

df_pivot['ucost'] = df_pivot['Cost'].str.replace(',', '').astype(int)
df_pivot = df_pivot.sort_values(by = ['ucost', "bm", 'Utm_campaign', "Time"], axis = 0, ascending=[False, True, False, True]).drop('ucost', axis=1)

res:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM