我有两个数据框 产品、用户 产品可以在多个类别中,所有类别都用分号分隔。 用户将对多个类别感兴趣,这些类别也用分号分隔。 现在我需要找到用户进行交互的所有内容 ID。
我试图拆分两个数据帧(产品、用户)并试图找到 isin()
值我得到这个错误。
users['intrestcategory'].str.split(";", n=1, expand=True)
A value is trying to be set on a copy of a slice from a DataFrame ValueError: Wrong number of items passed 0, placement implies 1
下面是数据帧的示例。
1)产品
Categories contentId
1
12;2 2
3
2 4
3;15 5
15 6
7
20 8
20;2 9
2)用户
userid intrestcategories
2 12;2
3 3
4 15
3) 最终输出
userid contentId
2 4
2 2
2 9
3 5
4 5
4 6
最佳答案
首先我们使用explode
(pandas 版本 >= 0.25.0)将每列的多个类别转换为多行,然后 merge
在类别上并删除重复项:
import pandas as pd
from numpy import nan
dfp = pd.DataFrame({'contentId': {0: nan, 1: 2.0, 2: nan, 3: 4.0, 4: 5.0, 5: 6.0, 6: nan, 7: 8.0, 8: 9.0}, 'Categories': {0: '1', 1: '12;2', 2: '3', 3: '2', 4: '3;15', 5: '15', 6: '7', 7: '20', 8: '20;2'}})
dfu = pd.DataFrame({'intrestcategories': {0: '12;2', 1: '3', 2: '15'}, 'userid': {0: 2, 1: 3, 2: 4}})
dfp.Categories = dfp.Categories.str.split(';')
dfp = dfp.explode('Categories')
dfu.intrestcategories = dfu.intrestcategories.str.split(';')
dfu = dfu.explode('intrestcategories')
dfp.dropna().merge(dfu,left_on='Categories',right_on='intrestcategories')[['userid','contentId']].drop_duplicates().astype(int)
结果:
userid contentId
0 2 2
2 2 4
3 2 9
4 3 5
5 4 5
6 4 6
关于python - 如何在 python 中将数据框与分号合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220001/