python pandas如果列字符串包含单词标志 [英] python pandas if column string contains word flag

查看:181
本文介绍了python pandas如果列字符串包含单词标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的python pandas dataframe df中添加一个标志,如果列Title中的条目包含单词test(大写或小写或全部大写),我想在其中添加T新列test.

I want to add a flag to my python pandas dataframe df, if an entry in the column Titlecontains the word test (upper or lower case or all Uppercase), I would like to add T in a new column test.

这给我一个错误,并不能解决所有大写情况:

This gives me an error and does not account for all uppercase scenarios:

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

ValueError: Length of values does not match length of index

推荐答案

您需要

You need contains with parameter case=Falseand na=False:

df['Test_Flag'] = np.where(df['Title'].str.contains("test", case=False, na=False), 'T', '')

示例:

df = pd.DataFrame({'Title':['test','Test',np.nan, 'a']})
df['Test_Flag'] = np.where(df['Title'].str.contains("test", case=False, na=False), 'T', '')
print (df)
  Title Test_Flag
0  test         T
1  Test         T
2   NaN          
3     a  

这篇关于python pandas如果列字符串包含单词标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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