[英]How to calculate the percentage of each value in a column follow each category in python pandas dataframe
[英]how to calculate percentage for each cell and replace tha value with result(%) using pandas dataframe?
這是示例示例:
input:
sub del wait
12 55 11
13 33 71
例如:第一行:del=55*100/12=458.33 等待=11*100/12=91.66
第二行:del=33*100/13=253.3 等待=71*100/13=546.01
最終輸出應該是:
sub del wait
12 458.33 91.66
13 253.3 546.01
選擇兩列,乘以100
並除以DataFrame.div
,然后在必要時使用DataFrame.round
重新分配列:
df[['del','wait']] = df[['del','wait']].mul(100).div(df['sub'], axis=0).round(2)
print (df)
sub del wait
0 12 458.33 91.67
1 13 253.85 546.15
或者除以由Series.to_numpy
創建的具有形狀 (N x 1) 的 numpy 數組,用於每行除法:
df[['del','wait']] = (df[['del','wait']] * 100 / df['sub'].to_numpy()[:, None]).round(2)
print (df)
sub del wait
0 12 458.333333 91.666667
1 13 253.846154 546.153846
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.