【Pandas】合并DataFrame

感情迁移 提交于 2020-03-09 04:58:40

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!