python - Pandas 列出两列之间的相似度

标签 python 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'

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

最佳答案

解决方案是使用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     25.0
1    100.0
2      0.0
dtype: float64

方程解释:

首先在等式中检查公共(public)元素:

df.apply(lambda x: len(set(x['list_left']) & set(x['list_right'])), 1)

输出:

0    1
1    2
2    0
dtype: int64

接下来,检查列表的不同元素并将其乘以:

df.apply(lambda x: float(len(set(x['list_left']) | set(x['list_right']))), 1)

输出:

0    4
1    2
2    4
dtype: float64

相似度由(共同元素/不同元素)*100 定义。因此对于第一行,它是1/4*100 = 0.25

关于python - Pandas 列出两列之间的相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016782/

相关文章:

python - 使用 Pandas 创建绘图并直接显示与使用 Matplotlib 类似的输出

python - `.astype(' 分类') 和 `pd.Category(...)` 之间的 Pandas 差异

python - 在python 3中查找表中名称第一个字符的频率分布

python - 将多索引数据帧拆分为 pandas 中的平面数据帧

python - 使用python的递归grep

Python selenium打印框架源码

python - 如何删除数据帧列中字符后的字符串的其余部分?

python - OpenCV-(-215 :Assertion failed) _src. 函数 'cv::warpPerspective' 中总计() > 0

python - pandas 中 lambda 函数的正确使用

python - Pandas.DataFrame.rename 方法中的参数 "index"是什么?