pandas panda更改了其他三列的列值条件

3okqufwl  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(147)

我有以下Pandas Dataframe :

df = pd.DataFrame({'pred': [1, 2, 3, 4],
                   'a': [0.4, 0.6, 0.35, 0.5],
                   'b': [0.2, 0.4, 0.32, 0.1],
                   'c': [0.1, 0, 0.2, 0.2],
                   'd': [0.3, 0, 0.1, 0.2]})

我想根据a、b、c、d列更改"pred"列的值,如下所示:

    • 如果**a的a列值大于b、c、d列值

以及

    • 如果**b、c或d列之一的值大于0.25

然后将"pred"中的值更改为0。因此结果应为:

pred    a       b         c      d
0   1        0.4    0.2      0.1    0.1
1   0        0.6    0.4      0.0    0.0
2   0        0.35   0.32      0.2   0.3
3   4        0.5    0.1      0.2    0.2

我该怎么做呢?

hmae6n7t

hmae6n7t1#

创建布尔条件/掩码,然后使用loc将值设置为0,其中条件为True

cols = ['b', 'c', 'd']
mask = df[cols].lt(df['a'], axis=0).all(1) & df[cols].gt(.25).any(1)
df.loc[mask, 'pred'] = 0
pred     a     b    c    d
0     1  0.40  0.20  0.1  0.1
1     0  0.60  0.40  0.0  0.0
2     0  0.35  0.32  0.2  0.3
3     4  0.50  0.10  0.2  0.2
2jcobegt

2jcobegt2#

import pandas as pd

def row_cond(row):
    m_val = max(row[2:])
    if row[1]>m_val and m_val>0.25:
        row[0] = 0
    return row

df = pd.DataFrame({'pred': [1, 2, 3, 4],
                   'a': [0.4, 0.6, 0.35, 0.5],
                   'b': [0.2, 0.4, 0.32, 0.1],
                   'c': [0.1, 0, 0.2, 0.2],
                   'd': [0.1, 0, 0.3, 0.2]})

new_df = df.apply(row_cond,axis=1)

输出:

pred    a       b       c       d
0   1.0     0.40    0.20    0.1     0.1
1   0.0     0.60    0.40    0.0     0.0
2   0.0     0.35    0.32    0.2     0.3
3   4.0     0.50    0.10    0.2     0.2

相关问题