1.创建DataFrame
df1 = pd.DataFrame(np.arange(0, 12).reshape(3, 4), columns=["A", "B", "C", "D"])
df2 = pd.DataFrame(np.arange(12, 24).reshape(3, 4), columns=["A", "B", "C", "D"])
2.直接合并
# pd.concat(),axis为0是纵向合并,为1是横向合并,ignore_index是否忽略索引
new_df = pd.concat([df1, df2], axis=0, ignore_index=True)
print(new_df)
# 输出结果:
# A B C D
# 0 0 1 2 3
# 1 4 5 6 7
# 2 8 9 10 11
# 3 12 13 14 15
# 4 16 17 18 19
# 5 20 21 22 23
3.outer、inner合并
df3 = pd.DataFrame(np.arange(0, 12).reshape(3, 4), columns=["A", "B", "C", "F"])
df4 = pd.DataFrame(np.arange(12, 24).reshape(3, 4), columns=["A", "C", "D", "E"])
new_df2 = pd.concat([df3, df4], axis=0, join="outer", ignore_index=True)
print(new_df2)
# 输出结果
# A B C D E F
# 0 0 1.0 2 NaN NaN 3.0
# 1 4 5.0 6 NaN NaN 7.0
# 2 8 9.0 10 NaN NaN 11.0
# 3 12 NaN 13 14.0 15.0 NaN
# 4 16 NaN 17 18.0 19.0 NaN
# 5 20 NaN 21 22.0 23.0 NaN
new_df3 = pd.concat([df3, df4], axis=0, join="inner", ignore_index=True)
print(new_df3)
# 输出结果:
# A C
# 0 0 2
# 1 4 6
# 2 8 10
# 3 12 13
# 4 16 17
# 5 20 21
来源:CSDN
作者:冰冷的希望
链接:https://blog.csdn.net/qq_39147299/article/details/104735005