python-3.x - 合并 2 个不同的数据框 - Python 3.6
问题描述
想要合并 2 个表格和空白应填充第一个表格行。
DF1:
Col1 Col2 Col3
A B C
DF2:
Col6 Col8
1 2
3 4
5 6
7 8
9 10
我期待结果如下:
Col1 Col2 Col3 Col6 Col8
A B C 1 2
A B C 3 4
A B C 5 6
A B C 7 8
A B C 9 10
解决方案
使用assign
,但随后有必要更改列的顺序:
df = df2.assign(**df1.iloc[0])[df1.columns.append(df2.columns)]
print (df)
Col1 Col2 Col3 Col6 Col8
0 A B C 1 2
1 A B C 3 4
2 A B C 5 6
3 A B C 7 8
4 A B C 9 10
或者并通过向前填充concat
替换s :NaN
ffill
df = pd.concat([df1, df2], axis=1).ffill()
print (df)
Col1 Col2 Col3 Col6 Col8
0 A B C 1 2
1 A B C 3 4
2 A B C 5 6
3 A B C 7 8
4 A B C 9 10
推荐阅读
- c++ - 有没有办法使用 Visual Studio 在 Xcode 中打开一个克隆的 git 项目?
- php - PHP - 返回带有用户数据的 URL 的搜索框
- pagination - TYPo3 9.5.5 中的默认分页小部件仅显示第一个结果
- java - 我在本地主机上的数据库和使用 Java 在线开发的网站的连接 URL 应该是什么?
- pandas - 我可以使用 .apply(lambda 函数根据条件返回值,同时跳过不满足条件的值吗?
- java - 嗨,我的 For 循环有问题,我对其进行了调试,但看不到给出结果的原因
- javascript - 将函数分配给变量而不调用
- javascript - 如何使用 JSON 从动态生成的表单中获取值
- azure-functions - Device Provisioning 自定义分配 - 在 azure 函数中设置初始 Device Twin
- python - 将值附加到三个列表的小函数