>我有以下数据帧
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
可能还有其他有效的解决方案,也许您可以尝试使用以下方法,如果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