何时合并vs concat两个Pandas数据帧是明智的?

2024-09-28 05:34:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有两个数据帧共享相同的索引,但具有不同的列。将两个数据帧合并到此处或concat更明智吗

import pandas as pd
from pandas import DataFrame

df1 = 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 merging
df3_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 concatenate
df3_concat = pd.concat([df1,df2], axis = 1)  

#result:      
#             gee  thanks  youre  welcome
# hey          1    foo      8    fotb
# yo           6    rhy      3     yuo

This link启发了这个问题。通常我总是使用concat,但我很好奇别人用什么或怎么想


Tags: dataframeindexfoodf1df2yowelcomehey
1条回答
网友
1楼 · 发布于 2024-09-28 05:34:46

我想这取决于你需要什么

默认情况下,^{}中的是inner连接,但可以将其更改为outerrightleft

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

^{}中默认为外部联接,但只能通过inner参数将其更改为inner

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

另外,如果想要加入数据帧列表,更简单、更快的方法是concat

如果希望左连接,则不能使用concat,因为未实现


有关^{}的更多信息

有关^{}的更多信息

相关问题 更多 >

    热门问题