我有两个主题模型,
topics1
和topics2
。它们是根据非常相似但不同的数据集创建的。因此,代表每个主题/集群的单词以及主题编号对于每个数据集都将不同。一个玩具示例如下所示:
import pandas as pd
topics1 = pd.DataFrame({'topic_num':[1,2,3],
'words':[['red','blue','green'],
['blue','sky','cloud'],
['eat','food','nomnom']]
})
topics2 = pd.DataFrame({'topic_num':[1,2,3],
'words':[['blue','sky','airplane'],
['blue','green','yellow'],
['mac','bit','byte']]
})
对于
topics1
中的每个主题,我想在topics2
中找到匹配次数最多的主题。在上面的示例中,在 topics1
中,topic_num 1 将与 topics2
中的 topic_num 2 匹配,而 topics1
中的 topic_num 2 将与 topics2
中的 topic_num 1 匹配。在这两种情况下,每行 3 个单词中的 2 个在数据帧中匹配。
有没有办法使用内置的
pandas
函数(例如 eq()
)找到它?我的解决方案只是迭代 topics1
中的每个单词和 topics2
中的每个单词。
您可以使用集合并广播比较:
s1 = topics1.set_index('topic_num')['words'].map(set)
s2 = topics2.set_index('topic_num')['words'].map(set)
tmp = (pd.DataFrame(s1.to_numpy()[:, None]
&s2.to_numpy(),
index=s1.index, columns=s2.index
)
.map(len)
)
out = tmp.idxmax(axis=1).where(tmp.gt(0).any(axis=1))