IIUC公司,
new_df = pd.crosstab(df.user_id,df.label,df.avg_price,aggfunc='mean')
new_df.columns = new_df.columns.map(lambda x : f'{x}_avg_price')
print(new_df)
label A_avg_price B_avg_price C_avg_price
user_id
11 217.3 312.1 1079.8
14 453.1 125.4 NaN
要匹配所需的输入,可以重置索引并将列标签重命名为
None
new_df = pd.crosstab(df.user_id,df.label,df.avg_price,aggfunc='mean')
new_df.columns = new_df.columns.map(lambda x : f'{x}_avg_price')
new_df.reset_index(inplace=True)
new_df.columns.name = None
print(new_df)
user_id A_avg_price B_avg_price C_avg_price
0 11 217.3 312.1 1079.8
1 14 453.1 125.4 NaN