python pandas 如果列字符串包含单词标志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43055050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:17:25  来源:igfitidea点击:

python pandas if column string contains word flag

pythonstringpandasnumpy

提问by jeangelj

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 Tin a new column test.

我想向我的 python pandas 数据框 df 添加一个标志,如果列Title中的条目包含单词test(大写或小写或全部大写),我想添加T一个新列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

回答by jezrael

You need containswith parameter case=Falseand na=False:

您需要contains带参数case=Falsena=False

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

Sample:

样本:

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