df["% Sales"] = df["Jan"]/df["Q1"]
q1_sales = df.groupby(["City"])["Jan","Feb","Mar", "Q1"].sum()
ql_sales.head()
Jan Feb Mar Q1
City
Los Angeles 44 40 54 138
想要获得该季度销售百分比的代码。希望它看起来像这样,每个月下面除以该季度的总销售额。
Jan Feb Mar
City
Los Angeles 31.9% 29% 39.1%
答案 0 :(得分:1)
使用:
new_df=q1_sales[q1_sales.columns.difference(['Q1'])]
new_df=(new_df.T/new_df.sum(axis=1)*100).T
print(new_df)
Feb Jan Mar
Los Angeles 28.985507 31.884058 39.130435
答案 1 :(得分:1)
尝试div
:
q1_sales[['Jan','Feb','Mar']].div(q1_sales['Q1']*0.01, axis='rows')
输出:
Jan Feb Mar
City
Los Angeles 31.884058 28.985507 39.130435