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
python pandas if column string contains word flag
提问by jeangelj
I want to add a flag to my python pandas dataframe df, if an entry in the column Title
contains the word test
(upper or lower case or all Uppercase), I would like to add T
in 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 contains
with parameter case=False
and na=False
:
您需要contains
带参数case=False
和na=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