Pandas 列出两列之间的相似性

我有一个df:


df = pd.DataFrame({'id': [123, 456, 789],

                   'list_left': [['dog', 'cat'],['dog', 'mouse'], ['dog', 'elephant']],

                   'list_right': [['cat', 'mouse', 'giraffe'], ['mouse', 'dog'], ['giraffe', 'gorilla']]})

我想找到字符串列表之间的相似性。这应该忽略顺序或长度(即['dog', 'mouse'],['mouse', 'dog']应该导致 100% 的相似性)。这是我的尝试(https://www.geeksforgeeks.org/python-percentage-similarity-of-lists/):


df['result'] = len(set(df['list_left']) & set(df2['list_right'][1])) / float(len(set(df['list_left']) | set(df['list_right']))) * 100

这会导致此错误:


TypeError                                 Traceback (most recent call last)

<ipython-input-136-3b1e1ee16eed> in <module>()

----> 1 df['new'] = len(set(df['list_left']) & set(df2['list_right'][1])) / float(len(set(df['list_left']) | set(df['list_right']))) * 100


TypeError: unhashable type: 'list'

与熊猫 df 中的列表列进行比较的好方法是什么?对于不同长度的字符串列表,列表之间的相似性是否具有逻辑意义?


肥皂起泡泡
浏览 216回答 2
2回答

呼如林

解决方案是使用apply:df.apply(lambda x: len(set(x['list_left']) & set(x['list_right'])) / float(len(set(x['list_left']) | set(x['list_right']))) * 100,1)输出:0&nbsp; &nbsp; &nbsp;25.01&nbsp; &nbsp; 100.02&nbsp; &nbsp; &nbsp; 0.0dtype: float64方程的解释:首先在等式中检查公共元素:df.apply(lambda x: len(set(x['list_left']) & set(x['list_right'])), 1)输出:0&nbsp; &nbsp; 11&nbsp; &nbsp; 22&nbsp; &nbsp; 0dtype: int64接下来,您检查列表的不同元素并将其乘以:df.apply(lambda x: float(len(set(x['list_left']) | set(x['list_right']))), 1)输出:0&nbsp; &nbsp; 41&nbsp; &nbsp; 22&nbsp; &nbsp; 4dtype: float64相似度由(共同元素/不同元素)*100 定义。所以对于第一行它是1/4*100 = 0.25。

慕妹3146593

这里解决方案不使用applys = df.list_left + df.list_rights1 = s.map(set)(s.str.len() - s1.str.len()) / s1.str.len() * 100Out[132]:0&nbsp; &nbsp; &nbsp;25.01&nbsp; &nbsp; 100.02&nbsp; &nbsp; &nbsp; 0.0dtype: float64
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python