计算数据框中行的比例

Calculate proportions of rows in dataframe

我有一个问题希望你能帮助解决。

我有一个包含多列的数据框,看起来像这样:

education   experience  ExpenseA    ExpenseB    ExpenseC
uni         yes         3           2            5
uni         no          7           6            8
middle      yes         2           0            8
high        no          12          5            8
uni         yes         3           7            5

费用 A、B 和 C 每行加起来应该是 10,但通常不是,因为数据收集不正确。对于不是这种情况的行,我想按比例分配。

The formula for this should be (cell value) / ((sum [ExpenseA] til [ExpenseC])/10)

示例第二行:总计 = 21 --> 单元格应为 (value / 2.1)

我如何迭代这些特定列的所有行?

我认为您需要将列的总和除以 DataFrame.iloc:

选择的前 2 列
df.iloc[:, 2:] = df.iloc[:, 2:].div(df.iloc[:, 2:].sum(axis=1).div(10), axis=0)
print (df)
  education experience  ExpenseA  ExpenseB  ExpenseC
0       uni        yes  3.000000  2.000000  5.000000
1       uni         no  3.333333  2.857143  3.809524
2    middle        yes  2.000000  0.000000  8.000000
3      high         no  4.800000  2.000000  3.200000
4       uni        yes  2.000000  4.666667  3.333333

或按 DataFrame.filter:

对具有 Expense 个子字符串的列求和
df1 = df.filter(like='Expense')

df[df1.columns] = df1.div(df1.sum(axis=1).div(10), axis=0)