为了账号安全,请及时绑定邮箱和手机立即绑定

什么时候合并与连接两个熊猫数据帧是明智的?

什么时候合并与连接两个熊猫数据帧是明智的?

Smart猫小萌 2022-09-13 10:14:08
假设有两个数据帧共享相同的索引但具有不同的列。在这里合并两个数据帧还是连接更聪明?import pandas as pdfrom pandas import DataFramedf1 = DataFrame(index = ['hey', 'yo'], columns = ['gee', 'thanks'], data = [[1,'foo'],[6,'rhy']]) df2 = DataFrame(index = ['hey', 'yo'], columns = ['youre', 'welcome'], data = [[8,'fotb'],[3,'yuo']])#using mergingdf3_merge = df1.merge(df2,left_index = True, right_index = True)  #result:      #             gee  thanks  youre  welcome# hey          1    foo      8    fotb# yo           6    rhy      3     yuo#using concatenatedf3_concat = pd.concat([df1,df2], axis = 1)  #result:      #             gee  thanks  youre  welcome# hey          1    foo      8    fotb# yo           6    rhy      3     yuo这个链接激发了这个问题。通常我总是使用,但我对别人使用或思考的东西感到好奇。concat
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

我认为这取决于,需要什么。

默认情况下,在 DataFrame.merge 中是联接,但可以将其更改为 或 。innerouterrightleft

df3_merge = df1.merge(df2,left_index = True, right_index = True)

在 concat 中默认为外连接,但可以将其更改为仅按参数:innerinner

df3_concat = pd.concat([df1,df2], axis = 1)

此外,如果需要数据帧的加入列表,更简单,更快捷的方法。concat

如果想要左联接,就不能使用,因为没有实现。concat


有关连接的更多信息

有关合并的详细信息。


查看完整回答
反对 回复 2022-09-13
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号