【问题标题】:How to merge 3 dataset in pandas如何在熊猫中合并 3 个数据集
【发布时间】:2018-08-19 19:56:58
【问题描述】:

我有 3 个数据集:restaurants.csv、users.csv 和 rating.csv。 Restaurant.csv 包含餐厅 ID 和一些功能。 Users.csv 包含用户 ID 和一些用户特征。 Raiting.csv 包含餐厅 ID、用户 ID 和对应评级。

place_id feature1 feature2 1 .. ..
2 .. ..

user_id feature1 feature2 1 .. ..
2 .. ..

place_id user_id raiting 1 1 2
2 1 3

我想合并这 3 个文件以获得一个数据集,其中包含餐厅、用户特征和相应的评分作为标签。我想得到如下数据集:

place_id user_id place_feature1 ... user_feature2 raiting 1 1 .. 2
2 2 .. 3

我该怎么做?

【问题讨论】:

  • 请您分享部分输入数据帧和您想要的输出。换句话说,一个minimal reproducible example。通过这种方式,我们可以确保我们提供的解决方案适合您。
  • 如果我的回答有帮助,别忘了。谢谢。

标签: python pandas csv merge


【解决方案1】:

我认为你需要双 merge 左连接:

示例数据帧

df1 = pd.DataFrame({'place_id':[1,2,3,4],
                   'B':[4,5,4,7],
                   'C':[7,8,9,4]})

print (df1)
   B  C  place_id
0  4  7         1
1  5  8         2
2  4  9         3
3  7  4         4

df2 = pd.DataFrame({'user_id':[1,2,3,4],
                   'D':[40,50,40,70],
                   'E':[70,80,90,40]})

print (df2)
    D   E  user_id
0  40  70        1
1  50  80        2
2  40  90        3
3  70  40        4

df3 = pd.DataFrame({'user_id':[1,2,3,4,1,2],
                   'place_id':[1,1,1,1,2,2],
                   'rating':[7,8,9,4,4,5]})

print (df3)
   place_id  rating  user_id
0         1       7        1
1         1       8        2
2         1       9        3
3         1       4        4
4         2       4        1
5         2       5        2

真实数据使用read_csv:

#df1 = pd.read_csv('restaurants.csv')
#df2 = pd.read_csv('users.csv')
#df3 = pd.read_csv('rating.csv')

df = df3.merge(df1, on='place_id', how='left').merge(df2, on='user_id', how='left')
print (df)
   place_id  rating  user_id  B  C   D   E
0         1       7        1  4  7  40  70
1         1       8        2  4  7  50  80
2         1       9        3  4  7  40  90
3         1       4        4  4  7  70  40
4         2       4        1  5  8  40  70
5         2       5        2  5  8  50  80

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 2021-01-28
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多