比较数据帧的多个列并将结果存储到新列中

2024-07-05 14:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下所示的数据(我已将“rule\u id”设置为索引):

rule_id  a   b   c  d
50378    2   0   0  5
50402    12  9   6  0
52879    0   4   3  2

使用此代码后:

^{pr2}$

我的数据如下:

rule_id  a   b   c  d  comp1  comp2  comp3  comp4
50378    2   0   0  5   100    NaN    NaN    100
50402    12  9   6  0   87.5   41.66  100    NaN
52879    0   4   3  2   NaN    87.5  41.66  100 

这里的'df'是存储我上面提到的数据的数据帧。 看第一排。根据我的代码,如果比较两列,第一列是非零值(2),第二列是0,那么新列中应该更新100,我可以实现,如果有多个非零值之间有比较(看第2行),那么比较是这样的:

9/12 *50 +50 = 87.5

那么

6/9 * 25 + 25 = 41.66

我可以实现,但是第三个比较列'c'和'd'(值在6和0之间)应该是:

0/6 *12.5 + 12.5 = 12.5

我很难做到。因此,不是第2行comp3中的100,而是12.5。最后一行也一样,值是4、3和2

这是我想要的结果:

rule_id  a   b   c  d  comp1  comp2  comp3  comp4
50378    2   0   0  5   100    NaN    NaN    100
50402    12  9   6  0   87.5   41.66  12.5   NaN
52879    0   4   3  2   NaN    87.5  41.66   12.5 

Tags: 数据代码iddfnanrulecomp1pr2
2条回答

为了参与进来,这里是对您的代码的贡献,对于coeff矩阵的定义,计算直接在整列上执行。在

初始化:

>>> df = pd.DataFrame([[2, 0, 0, 5], [12, 9, 6, 0], [0, 4, 3, 2]],
...                    index=[50378, 50402, 52879],
...                    columns=['a', 'b', 'c', 'd'])
>>> df 
        a   b   c   d
50378   2   0   0   5
50402   12  9   6   0
52879   0   4   3   2

然后计算系数:

^{pr2}$

它给出了:

        a   b   c     d
50378   50  100 100   50
50402   50  25  12.5  100
52879   100 50  25    12.5

(对于您的问题的核心,John指出该函数缺少条件,因此不需要我参与。)

你说:

the third comparison between column 'c' and 'd' which is between value 6 and 0 should be:

0/6 *12.5 + 12.5 = 12.5

但你的代码说:

   conditions = [(df[col1] == 0) & (df[col2] == 0), (df[col1] != 0) & (df[col2] == 0), (df[col1] == df[col2]),
                  (df[col1] != 0) & (df[col2] != 0)]

   choices = [np.nan , 100 , coeff[col1] , df[col2]/df[col1]*coeff[col1]+coeff[col1]]

显然(6, 0)满足{},因此产生{}。您似乎认为它应该满足condition[3],也就是说两者都不是零,但是(6, 0)不满足这个条件,即使满足了,它也不重要,因为{}首先匹配,而{}选择第一个匹配。在

也许你想要这样的东西:

    conditions = [(df[col1] == 0) & (df[col2] == 0), (df[col1] == df[col2])]
    choices = [np.nan , coeff[col1]]
    default = df[col2]/df[col1]*coeff[col1]+coeff[col1]

    df['comp{}'.format(i)] = np.select(conditions , choices, default)

相关问题 更多 >