Python 何时合并vs concat两个熊猫数据帧是明智的?
假设有两个数据帧共享相同的索引,但具有不同的列。将两个数据帧合并到此处或concat更明智吗Python 何时合并vs concat两个熊猫数据帧是明智的?,python,pandas,dataframe,merge,concatenation,Python,Pandas,Dataframe,Merge,Concatenation,假设有两个数据帧共享相同的索引,但具有不同的列。将两个数据帧合并到此处或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 = ['you
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
激发了这个问题。通常我总是使用concat,但我很好奇别人用什么或怎么想。我认为这取决于需要什么 默认情况下,in是
内部
连接,但可以将其更改为外部
、右侧
或左侧
df3_merge = df1.merge(df2,left_index = True, right_index = True)
默认为外部联接,但只能通过内部
参数将其更改为内部
:
df3_concat = pd.concat([df1,df2], axis = 1)
另外,如果想要连接数据帧列表,则更简单、更快的方法是concat
method
如果想要左联接,则不能使用concat
,因为未实现
有关的更多信息 有关的更多信息