Pandas 包含条件 returns True 但想要 return 作为 1 或 0 - 创建 series/dataframe 列
Pandas contains condition returns True but want to return as 1 or 0 - creation of a series/dataframe column
我有一个数据框,其中一列包含字符串值。我想遍历指定列中的每一行,以查看该值是否包含我要查找的单词。如果是,我希望它为 return int 值 1,如果不是,则为 0.
df['2'] = df['Col2'].str.lower().str.contains('word')
我只能拿到returnTrue
或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) 添加到您的布尔列即可。或者只使用应用函数 line.look 下面的例子。
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
我有一个数据框,其中一列包含字符串值。我想遍历指定列中的每一行,以查看该值是否包含我要查找的单词。如果是,我希望它为 return int 值 1,如果不是,则为 0.
df['2'] = df['Col2'].str.lower().str.contains('word')
我只能拿到returnTrue
或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) 添加到您的布尔列即可。或者只使用应用函数 line.look 下面的例子。
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