📜  使用 merge() 连接两个 Pandas DataFrame

📅  最后修改于: 2022-05-13 01:55:11.240000             🧑  作者: Mango

使用 merge() 连接两个 Pandas DataFrame

让我们看看如何使用merge()函数连接两个 Pandas DataFrame。

合并()

示例 1:合并两个具有相同数量元素的 Dataframe:

# importing the module
import pandas as pd
  
# creating the first DataFrame
df1 = pd.DataFrame({"fruit" : ["apple", "banana", "avocado"],
                    "market_price" : [21, 14, 35]})
display("The first DataFrame")
display(df1)
  
# creating the second DataFrame
df2 = pd.DataFrame({"fruit" : ["banana", "apple", "avocado"],
                    "wholesaler_price" : [65, 68, 75]})
display("The second DataFrame")
display(df2)
  
# joining the DataFrames
display("The merged DataFrame")
pd.merge(df1, df2, on = "fruit", how = "inner")

输出 :

示例 2:合并两个具有不同数量元素的 Dataframe:

# importing the module
import pandas as pd
  
# creating the first DataFrame
df1 = pd.DataFrame({"fruit" : ["apple", "banana", 
                               "avocado", "grape"],
                    "market_price" : [21, 14, 35, 38]})
display("The first DataFrame")
display(df1)
  
# creating the second DataFrame
df2 = pd.DataFrame({"fruit" : ["apple", "banana", "grape"],
                    "wholesaler_price" : [65, 68, 71]})
display("The second DataFrame")
display(df2)
  
# joining the DataFrames
# here both common DataFrame elements are in df1 and df2, 
# so it extracts apple, banana, grapes from df1 and df2.  
display("The merged DataFrame")
pd.merge(df1, df2, on = "fruit", how = "inner")

输出 :

如果我们使用how = "Outer" ,它将返回 df1 和 df2 中的所有元素,但如果元素列为空,则返回 NaN 值。

pd.merge(df1, df2, on = "fruit", how = "outer")

输出 :

如果我们使用how = "left" ,它将返回左侧 DataFrame 中存在的所有元素。

pd.merge(df1, df2, on = "fruit", how = "left")

输出 :

如果我们使用how = "right" ,它会返回正确 DataFrame 中存在的所有元素。

pd.merge(df1, df2, on = "fruit", how = "right")

输出 :