python - 插入多行索引
问题描述
我正在寻找一种在 a 中间插入行的简洁方法,DataFrame
以便将插入点之后的行向前推。它看起来像这样:
Data Frame A Data Frame B
Idx | C1 | C2 Idx | C1 | C2
----+----+---- ----+----+----
0 | 12 | 31 0 | 49 | 67
1 | 64 | 98 1 | 25 | 63
2 | 47 | 10
Inserting B to A[2]:
Idx | C1 | C2
----+----+----
0 | 12 | 31
1 | 64 | 98
2 | 49 | 67 # B[0]
3 | 25 | 63 # B[1]
4 | 47 | 10
这必须针对多个数据帧,或者更确切地说是原始数据的切片来完成。总是可以选择循环遍历pd.concat
切片和插入索引,但是对于像pandas
我这样的库,我希望有人已经想出了我没有遇到的答案。
append
不太好用,但很接近。实际上存在df.insert
,但它是用于列的。我会很感激任何关于有用文档的指针。
沙盒:
a = pd.DataFrame([[1, 2], [2, 3], [3, 4]])
b = pd.DataFrame([[4, 5], [5, 6]])
解决方案
我认为最好的方法就是切片和连接:
insertion_point = 2
pd.concat([a.iloc[:insertion_point], b, a.iloc[insertion_point:]]).reset_index(drop=True)
0 1
0 1 2
1 2 3
2 4 5
3 5 6
4 3 4
推荐阅读
- typescript - 谷歌云函数错误“加载用户代码时函数失败。” 带有打字稿功能
- c++ - 我是否需要在 CUDA 中跨多个 GPU 镜像输入缓冲区/纹理?
- c++ - 未定义对 _intel_fast_memcpy 的引用 _intel_fast_memmove
- php - Laravel 从数据库数组中获取数据不起作用
- sql - 如何创建一个查询,该查询采用两列并按最新版本过滤每列 A 按列 B 中的最新版本号?
- wordpress - 革命滑块插件资产未从 CDN 加载
- javascript - 在单独的 Javascript 方法中调用 appendGrid 变量
- javascript - 如何为嵌套数组中的二级元素的状态正确创建事件处理(React)
- python - 如何有一个可变的变化量?
- android - 使用 Java 10 构建的 Android 使用库