📌  相关文章
📜  合并两个具有相同列名的数据框

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

合并两个具有相同列名的数据框

为了合并具有相同列名的两个数据框,我们将使用 pandas.concat()。该函数完成了与 Pandas 对象轴一起执行串联操作的所有繁重工作,同时在其他轴上执行索引(如果有)的可选设置逻辑(并集或交集)。

方法

  • 导入模块
  • 创建或加载第一个数据帧
  • 创建或加载第二个数据框
  • 基于相同的列名连接
  • 显示结果

以下是描述如何合并具有相同列名的两个数据框的各种示例:

示例 1:

Python3
# import module
import pandas as pd
  
# assign dataframes
data1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                     columns=['A', 'B', 'C'])
  
data2 = pd.DataFrame([[3, 4], [5, 6]],
                     columns=['A', 'C'])
  
# display dataframes
print('Dataframes:')
display(data1)
display(data2)
  
# merge two data frames
print('After merging:')
pd.concat([data1, data2], axis=0)


Python3
# import module
import pandas as pd
  
# assign dataframes
data1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
data2 = pd.DataFrame([[52, 'C'], [25, 'A']],
                     columns=['Students', 'Section'])
  
# display dataframes
print('Dataframes:')
display(data1)
display(data2)
  
# merge two data frames
print('After merging:')
pd.concat([data1, data2], axis=0)


Python3
# import module
import pandas as pd
  
# assign dataframes
data1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B'],
                      [25, 70.7, 'C']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
data2 = pd.DataFrame([[30, 70.2, 'A'], [25, 65.2, 'B'],
                      [35, 77.7, 'C']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
  
# display dataframes
print('Dataframes:')
display(data1)
display(data2)
  
# merge two data frames
print('After merging:')
pd.concat([data1, data2], axis=0)


输出:



示例 2:

蟒蛇3

# import module
import pandas as pd
  
# assign dataframes
data1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
data2 = pd.DataFrame([[52, 'C'], [25, 'A']],
                     columns=['Students', 'Section'])
  
# display dataframes
print('Dataframes:')
display(data1)
display(data2)
  
# merge two data frames
print('After merging:')
pd.concat([data1, data2], axis=0)

输出:

示例 3:

蟒蛇3

# import module
import pandas as pd
  
# assign dataframes
data1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B'],
                      [25, 70.7, 'C']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
data2 = pd.DataFrame([[30, 70.2, 'A'], [25, 65.2, 'B'],
                      [35, 77.7, 'C']],
                     columns=['Students', 'Avg Marks', 'Section'])
  
  
# display dataframes
print('Dataframes:')
display(data1)
display(data2)
  
# merge two data frames
print('After merging:')
pd.concat([data1, data2], axis=0)

输出: