Python Pandas contains条件返回True,但希望返回为1或0-创建系列/数据帧列
我有一个数据框,其中一列中有字符串值。我想迭代指定列中的每一行,以查看该值是否包含我要查找的单词。如果是,我希望它返回int值1,如果不是,则返回0Python Pandas contains条件返回True,但希望返回为1或0-创建系列/数据帧列,python,pandas,dataframe,if-statement,contains,Python,Pandas,Dataframe,If Statement,Contains,我有一个数据框,其中一列中有字符串值。我想迭代指定列中的每一行,以查看该值是否包含我要查找的单词。如果是,我希望它返回int值1,如果不是,则返回0 df['2'] = df['Col2'].str.lower().str.contains('word') 我只能让它返回True或False Col1 Col2 1 hello how are you 0 2 that is a big word
df['2'] = df['Col2'].str.lower().str.contains('word')
我只能让它返回True
或False
Col1 Col2
1 hello how are you 0
2 that is a big word 1
3 this word is bad 1
4 tonight tonight 0
很容易做到。只需将.astype(int)添加到布尔列即可。或者只对一行使用apply函数
df = pd.DataFrame(["hello how are you","that is a big word","this word is bad","tonight tonight"],columns=["Col1"])
# Method 1
df["Col2"] = df["Col1"].str.lower().str.contains('word')
df["Col2"] = df["Col2"].astype(int)
# Method 2
df["Col2"] = df["Col1"].apply(lambda x: 1 if "word" in x.lower() else 0)
df
Col1 Col2
0 hello how are you 0
1 that is a big word 1
2 this word is bad 1
3 tonight tonight 0
您只需添加
.astype(int)
即可将布尔值更改为整数。