Python:在列表的列上合并两个Pandas数据框
问题描述:
我需要基于一列名为作者"的列表来找到两个熊猫数据框之间的交集.>在此处输入图片描述
I need to find intersection between two pandas dataframes based on a column of lists named "authors".enter image description here
但是我得到了这个错误在此处输入图片描述
but instead i get this error enter image description here
答
You cannot merge on a list, because list cannot be hashed, see this. One option would be to create an additional column by converting list to string and merge on it, e.g.:
df['authors_as_string'] = df['authors'].apply(lambda x: "-".join(x))
这将产生:
id authors authors_as_string
0 1 [a, b, c] a-b-c
1 2 [a, b, c] a-b-c
2 3 [a, b] a-b
3 4 [a, c] a-c
然后,您可以在第三列上进行合并.
Then you can merge on that third column.
或者,您可以尝试在该问题中发布的其他解决方案.
Alternatively you can try other solutions posted in that question.