pandas 根据另一列替换值条件 [英] pandas replace values condition based on another column
本文介绍了 pandas 根据另一列替换值条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框:
I have a dataframe that looks like this:
col1 col2
Yes 23123
No 23423423
Yes 34234
No 13213
我想替换 col2 中的值,以便如果 col1 中的是"则返回空白,如果否"则返回初始值
I want to replace values in col2 so that if 'Yes' in col1 then return blank and if 'No' return the initial value
我想看这个:
col1 col2
Yes
No 23423423
Yes
No 13213
我已经试过了,但是否"返回无:
I have tried this but 'No' is returning None:
def map_value(x):
if x in ['Yes']:
return ''
else:
return None
df['col2'] = df['col1'].apply(map_value)
推荐答案
有很多方法可以解决这个问题,其中之一是
there are many ways to go about this, one of them is
df.loc[df.col1 == 'Yes', 'col2'] = ''
输出:
col1 col2
Yes
No 23423423
Yes
No 13213
这篇关于 pandas 根据另一列替换值条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文