python - Pandas Dataframe 合并多键

标签 python pandas dataframe multiple-columns

<分区>

每个人。

我有一个关于 DataFrame Merge 的问题。

我用的是DF1、DF2。

DF1 有 UserID、ContentID、Genre Column。 DF2 有 UserID、ContentID、Rating Column。

我想使用多列键( UserID, ContentID ) 然后匹配行Rating显示,没有匹配行是NAN

请检查下面的 CSV,

请帮帮我,谢谢

DataFrame1

UserID ContentID Genre 
U-1    C-1       G-1
U-1    C-2       G-2
U-1    C-3       G-3
U-2    C-1       G-1
U-2    C-2       G-2
U-2    C-3       G-3
U-3    C-1       G-1
U-3    C-2       G-2
U-3    C-3       G-3


DataFrame2
UserID ContentID Rating
U-1    C-1       3
U-1    C-2       3
U-2    C-2       3
U-3    C-1       3

Want Result
UserID ContentID Genre Rating
U-1    C-1       G-1   3
U-1    C-2       G-2   3
U-1    C-3       G-3   NAN
U-2    C-1       G-1   NAN
U-2    C-2       G-2   3
U-2    C-3       G-3   NAN
U-3    C-1       G-1   3
U-3    C-2       G-2   NAN
U-3    C-3       G-3   NAN

最佳答案

简单的合并

df1.merge(df2,on=['UserID','ContentID'],how='left')
Out[531]: 
  UserID ContentID Genre  Rating
0    U-1       C-1   G-1     3.0
1    U-1       C-2   G-2     3.0
2    U-1       C-3   G-3     NaN
3    U-2       C-1   G-1     NaN
4    U-2       C-2   G-2     3.0
5    U-2       C-3   G-3     NaN
6    U-3       C-1   G-1     3.0
7    U-3       C-2   G-2     NaN
8    U-3       C-3   G-3     NaN

关于python - Pandas Dataframe 合并多键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922610/

相关文章:

python - 如何在 Python 3 中从 R 重现基于 SHA256 的 HMAC

python - 错误 : type object 'Keys' has no attribute 'chord'

python - 使用 python 将数字(基于计算)格式化为小数点后两位的百分比

python - 列值到单字符串观察

python - 合并数据帧以包含指示行属于哪些数据帧的列

python - 在 Pandas DataFrame 中构建多重索引

python - 如何创建一个返回另一个模块的 python 模块

python - 在 Pandas 中,如何仅使用 True 系列 bool 值对行进行求和

Python 将 lambda 函数应用于 csv 文件(大文件)

python - 根据具有相同形状的其他 data.frame 中的值替换 data.frame 中的值(Python)