python:合并2个数据帧
我想使用python的pandas连接如下所示的两个数据帧:python:合并2个数据帧,python,pandas,left-join,Python,Pandas,Left Join,我想使用python的pandas连接如下所示的两个数据帧: customer_orders = pd.DataFrame({'customerID': [1, 2, 2, 1], 'customerName': ['John', 'Anna', 'Anna', 'John'], 'customerAge': [21, 45, 45, 21], 'orderID': [255,
customer_orders = pd.DataFrame({'customerID': [1, 2, 2, 1],
'customerName': ['John', 'Anna', 'Anna', 'John'],
'customerAge': [21, 45, 45, 21],
'orderID': [255, 256, 257, 258],
'paymentType': ['visa', 'bank', 'master', 'paypal']})
这就产生了:
customerAge customerID customerName orderID paymentType
0 21 1 John 255 visa
1 45 2 Anna 256 bank
2 45 2 Anna 257 master
3 21 1 John 258 paypal
orderID price productName
0 255 9.99 filter
1 255 23.40 cosmetic
2 257 15.89 shampoo
3 258 3.99 tissues
4 255 89.50 elecBrush
5 257 23.40 cosmetic
及
这就产生了:
customerAge customerID customerName orderID paymentType
0 21 1 John 255 visa
1 45 2 Anna 256 bank
2 45 2 Anna 257 master
3 21 1 John 258 paypal
orderID price productName
0 255 9.99 filter
1 255 23.40 cosmetic
2 257 15.89 shampoo
3 258 3.99 tissues
4 255 89.50 elecBrush
5 257 23.40 cosmetic
到下面这样的地方
预期产量
据我所知,这是一个SQL左连接。但是使用
all = customer_orders.join(order_products, on="orderID", how='left', lsuffix='_left', rsuffix='_right')
不给我我想要的太少的行和NaN,而不是第二个表的值
我错过了什么?左边?不,这是外部连接
customer_orders.merge(order_products, on="orderID", how='outer')
customerAge customerID customerName orderID paymentType price \
0 21 1 John 255 visa 9.99
1 21 1 John 255 visa 23.40
2 21 1 John 255 visa 89.50
3 45 2 Anna 256 bank NaN
4 45 2 Anna 257 master 15.89
5 45 2 Anna 257 master 23.40
6 21 1 John 258 paypal 3.99
productName
0 filter
1 cosmetic
2 elecBrush
3 NaN
4 shampoo
5 cosmetic
6 tissues
尝试使用合并
据我所知,这是可行的。除了否决票,我可以要求一些关于答案的反馈,以便我可以改进吗?他们仍然没有留下任何理由…我没有否决你!你的回答是正确的,也是我所需要的。我的错误是使用join而不是merge index而不是column另请参见:@user2952361谢谢。可能是某个人不太欣赏我的内容。很高兴它起到了作用。真的很有趣,pandas具有与SQL相同的功能。我只是对pandas有多复杂很感兴趣,它能很好地与python一起用于机器学习应用程序+1现在这正是OP的解决方案。
all = customer_orders.merge(order_products, on="orderID", how='left')