如何将两列都与字符串列表进行比较并创建一个具有唯一项的新列? [英] How to compare two columns both with list of strings and create a new column with unique items?

查看:24
本文介绍了如何将两列都与字符串列表进行比较并创建一个具有唯一项的新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列都带有字符串列表.基本上是一列 df['products'] 全部大写.另一列是产品描述df['desc'].

I have two columns both with list of strings. Basically one column df['products'] which are in all capitals. The other column is product description df['desc'].

我想检查 df['products'] 中的所有项目都存在于 df['desc'] 中,并从中创建一个新列.

I want to check what all items in df['products'] are present in df['desc'] and make a new column out of it.

我尝试了以下代码:

df['uniq'] = df.apply(lambda x : [i for i in x['products'] if i.lower() in x['desc']])

我检查了其他类似的问题并构建了上述代码,但它不起作用.

I checked the other similar questions and built the above code, but it's not working.

数据看起来像这样:

推荐答案

如果需要检查每行,似乎需要添加 axis=1 :

It seems you need add axis=1 if need check per rows:

df = pd.DataFrame({'products':[['A','B'],['D','C']],
                   'desc':[['a', 'c'],['c', 'e']]})

df['uniq'] = df.apply(lambda x: [i for i in x['products'] if i.lower() in x['desc']], axis=1)
print (df)
     desc products uniq
0  [a, c]   [A, B]  [A]
1  [c, e]   [D, C]  [C]

这篇关于如何将两列都与字符串列表进行比较并创建一个具有唯一项的新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆