排除条件创造

2024-04-25 05:42:55 发布

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

我有以下数据帧

col1 col2 col3
a    b    c
d    e    f
g    h    i

我写了以下内容

df['col1'] = np.where((df['col2'].str.contains('b',case = False,regex=True,na=False)) & 
                      (df['col3'].str.contains('c',case = False,regex=True,na=False)),'s', 'o')

我现在明白了

col1 col2 col3
s    b    c
o    e    f
o    h    i

我现在想做下面的事情,其中col1不等于s

df['col1'] = np.where((df['col1'] != 's') &
                      (df['col2'].str.contains('e',case = False,regex=True,na=False)) & 
                      (df['col3'].str.contains('f',case = False,regex=True,na=False)),'z','x')

我想要以下

col1 col2 col3
s    b    c
z    e    f
x    h    i

但我得到了这个

col1 col2 col3
x    b    c
z    e    f
x    h    i

我希望逻辑不改变col1中的s


Tags: 数据falsetruedfnpwhere事情regex
1条回答
网友
1楼 · 发布于 2024-04-25 05:42:55

可能还有其他有效的解决方案,可能您可以尝试使用以下方法,其中如果col1等于s,则返回s,否则使用np.where和其他条件:

df['col1'] = np.where((df['col1'] == 's'), 's', 
                      np.where((df['col2'].str.contains('e',case = False,regex=True,na=False)) & 
                               (df['col3'].str.contains('f',case = False,regex=True,na=False)),
                                'z','x')
                     ) 
print(df)

结果:

  col1 col2 col3
0    s    b    c
1    z    e    f
2    x    h    i

更新:

有关更多仍带有where的条件:

df['col1'] = np.where((df['col1'] == 's'), 's', 
                      np.where((df['col1'] == 'z'), 'z',
                      np.where((df['col2'].str.contains('e',case = False,regex=True,na=False)) & 
                               (df['col3'].str.contains('f',case = False,regex=True,na=False)),
                                'z','x')
                               )
                     ) 
print(df)

使用应用程序:

首先我们可以创建函数,然后应用于dataframe

def function(row):
    if row['col1'] == 's':
        return 's'
    elif row['col1'] == 'z':
        return 'z'
    elif ('e' in row['col2'].lower()) and 'f' in row['col3'].lower():
        return 'z'
    else:
        return 'x'

现在,将函数应用于数据帧:

df['col1'] = df.apply(function, axis=1)
print(df)

结果:

  col1 col2 col3
0    s    b    c
1    z    e    f
2    x    h    i

相关问题 更多 >