Python Pandas-无法从另一个数据框列的列中识别字符串

时间:2019-06-16 14:51:39

标签: python pandas dataframe text contains

我有一个包含以下数据的数据框:

enter image description here

现在我试图使用isIn方法来产生一个新列,如果col_a在col_b中,那么在这种情况下,我试图产生以下输出:

enter image description here

为此,我正在使用以下代码:

df['res'] = df.col_a.isin(df.col_b)

但是它总是返回FALSE。我也尝试这样做:df['res'] = df.col_b.isin(df.col_a) 但是结果相同...所有行都为FALSE。

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以按col_a来检查col_b中的值是否在每行apply中:

df['res'] = df.apply(lambda x: x.col_a in x.col_b, axis=1)

或通过列表理解:

df['res'] = [a in b for a, b in zip(df.col_a, df.col_b)]

编辑:错误显然意味着缺少值,因此if-else语句是必需的:

df = pd.DataFrame({'col_a':['SQL','Java','C#', np.nan, 'Python', np.nan],
                   'col_b':['I.like_SQL_since_i_used_to_ETL',
                            'I like_programming_SQL.too',
                            'I prefer Java',
                            'I like beer',
                             np.nan,
                             np.nan]})
print (df)

df['res'] = df.apply(lambda x: x.col_a in x.col_b 
                               if (x.col_a == x.col_a) and (x.col_b == x.col_b) 
                               else False, axis=1)

df['res1'] = [a in b if (a == a) and (b == b) else False for a, b in zip(df.col_a, df.col_b)]
print (df)
    col_a                           col_b    res   res1
0     SQL  I.like_SQL_since_i_used_to_ETL   True   True
1    Java      I like_programming_SQL.too  False  False
2      C#                   I prefer Java  False  False
3     NaN                     I like beer  False  False
4  Python                             NaN  False  False
5     NaN                             NaN  False  False