python pandas列以其他两个列值为条件 [英] python pandas column conditional on two other column values

查看:423
本文介绍了python pandas列以其他两个列值为条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个或另一列具有值,python pandas中是否有一种方法可以应用条件?

Is there a way in python pandas to apply a conditional if one or another column have a value?

对于一列,我知道可以使用以下代码来在标题"列中包含"test"一词时应用测试标志.

For one column, I know I can use the following code, to apply a test flag if the column Title includes the word "test".

df['Test_Flag'] = np.where(df['Title'].str.contains("test|Test"), 'Y', '')

但是,如果我想说一下列标题或列副标题中是否包含单词"test",请添加测试标记,我该怎么做?

But if I would like to say if column title or column subtitle include the word "test", add the test flag, how could I do that?

这显然行不通

df['Test_Flag'] = np.where(df['Title'|'Subtitle'].str.contains("test|Test"), 'Y', '')

推荐答案

pattern = "test|Test"
match = df['Title'].str.contains(pattern) | df['Subtitle'].str.contains(pattern)
df['Test_Flag'] = np.where(match, 'Y', '')

这篇关于python pandas列以其他两个列值为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆