【问题标题】:When is it smart to merge vs concat two pandas dataframes?什么时候合并和连接两个熊猫数据框比较聪明?
【发布时间】:2020-03-24 08:25:29
【问题描述】:

假设有两个数据帧共享相同的索引但具有不同的列。在这里合并两个数据框还是 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,但我很好奇其他人的使用或想法。

【问题讨论】:

    标签: python pandas dataframe merge concatenation


    【解决方案1】:

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

    默认情况下,在DataFrame.merge 中加入inner,但可以将其更改为outerrightleft

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

    concat 中默认为外连接,但只能通过inner 参数将其更改为inner

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

    另外如果想加入DataFrames列表,更简单更快捷的是concat方法。

    如果要左连接,concat不能用,因为没有实现。


    更多关于concat的信息。

    更多关于merge的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      相关资源
      最近更新 更多