我的数据如下所示。我想用权重列划分每隔一行。有没有自动化的方法来做到这一点?我的数据有几列。
我要找的是A / Weight的结果应该在A栏中替换,C / Weight的结果应该在C栏中替换,依此类推,直到最后一对列。
A B C D Weight
0 2.056494 -3.002088 0.516822 -1.338846 0.40
1 0.082295 1.387734 -0.495226 1.119553 0.50
2 0.298618 -0.130158 0.804705 -0.120110 0.25
3 0.178088 1.137238 1.331856 -0.472720 0.50
4 -0.378670 1.649041 -0.240723 2.044113 0.65
5 3.602587 1.152502 -0.170646 -0.961922 0.50
6 -0.285846 -0.154891 1.492879 0.752487 0.56
7 -0.412809 1.076796 -2.001025 -0.954021 0.25
我有类似的东西,但它不起作用:
results=results.iloc[:, 0::2].div(results['Weight'], axis=0)
以下代码适用于其他所有列(B / A和D / C)。但是我只需要“权重”列就需要分母静态。
results_201.iloc[:,1::2] /= results_201.iloc[:,::2].values
感谢您阅读本文并寻求帮助!
答案 0 :(得分:1)
我们需要broadcasting
。因此,一种方法涉及使用底层数组数据进行原位编辑,如此 -
df.iloc[:,:-1:2] = df.iloc[:,:-1:2].values / df.iloc[:,[-1]].values
示例运行 -
In [62]: df
Out[62]:
A B C D Weight
0 2.0565 -3.0021 0.5168 -1.3388 0.4000
1 0.0823 1.3877 -0.4952 1.1196 0.5000
2 0.2986 -0.1302 0.8047 -0.1201 0.2500
3 0.1781 1.1372 1.3319 -0.4727 0.5000
4 -0.3787 1.6490 -0.2407 2.0441 0.6500
5 3.6026 1.1525 -0.1706 -0.9619 0.5000
6 -0.2858 -0.1549 1.4929 0.7525 0.5600
7 -0.4128 1.0768 -2.0010 -0.9540 0.2500
In [63]: df.iloc[:,:-1:2] = df.iloc[:,:-1:2].values / df.iloc[:,[-1]].values
In [64]: df
Out[64]:
A B C D Weight
0 5.1412 -3.0021 1.2921 -1.3388 0.4000
1 0.1646 1.3877 -0.9905 1.1196 0.5000
2 1.1945 -0.1302 3.2188 -0.1201 0.2500
3 0.3562 1.1372 2.6637 -0.4727 0.5000
4 -0.5826 1.6490 -0.3703 2.0441 0.6500
5 7.2052 1.1525 -0.3413 -0.9619 0.5000
6 -0.5104 -0.1549 2.6659 0.7525 0.5600
7 -1.6512 1.0768 -8.0041 -0.9540 0.2500
更简单的替代方法是将整个数据作为数组视图并在该数组本身上进行处理 -
In [96]: df
Out[96]:
A B C D Weight
0 2.0565 -3.0021 0.5168 -1.3388 0.4000
1 0.0823 1.3877 -0.4952 1.1196 0.5000
2 0.2986 -0.1302 0.8047 -0.1201 0.2500
3 0.1781 1.1372 1.3319 -0.4727 0.5000
4 -0.3787 1.6490 -0.2407 2.0441 0.6500
5 3.6026 1.1525 -0.1706 -0.9619 0.5000
6 -0.2858 -0.1549 1.4929 0.7525 0.5600
7 -0.4128 1.0768 -2.0010 -0.9540 0.2500
In [97]: a = df.values
In [98]: a[:,:-1:2] /= a[:,[-1]]
In [99]: df
Out[99]:
A B C D Weight
0 5.1412 -3.0021 1.2921 -1.3388 0.4000
1 0.1646 1.3877 -0.9905 1.1196 0.5000
2 1.1945 -0.1302 3.2188 -0.1201 0.2500
3 0.3562 1.1372 2.6637 -0.4727 0.5000
4 -0.5826 1.6490 -0.3703 2.0441 0.6500
5 7.2052 1.1525 -0.3413 -0.9619 0.5000
6 -0.5104 -0.1549 2.6659 0.7525 0.5600
7 -1.6512 1.0768 -8.0041 -0.9540 0.2500