是否可以使用pandas在数据框中的任意位置插入行?

Tro*_*oas 44 python pandas

我有一个类似于这个的DataFrame对象:

       onset    length
1      2.215    1.3
2     23.107    1.3
3     41.815    1.3
4     61.606    1.3
...
Run Code Online (Sandbox Code Playgroud)

我想要做的是在某个索引值指定的位置插入一行,并相应地更新以下索引.例如:

       onset    length
1      2.215    1.3
2     23.107    1.3
3     30.000    1.3  # new row
4     41.815    1.3
5     61.606    1.3
...
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

bdi*_*nte 47

你可以切片并使用concat来获得你想要的东西.

line = DataFrame({"onset": 30.0, "length": 1.3}, index=[3])
df2 = concat([df.iloc[:2], line, df.iloc[3:]]).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

这将在示例输出中生成数据帧.据我所知,concat是在熊猫中实现插入类型操作的最佳方法,但不可否认,我绝不是熊猫专家.


Rei*_*mar 15

我发现它更易于排序而不是切片和连接.

line = DataFrame({"onset": 30.0, "length": 1.3}, index=[2.5])
df = df.append(line, ignore_index=False)
df = df.sort_index().reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)


Ser*_*oGM 6

我认为没有 concat 或 append 会更容易:

df.loc[2.5] = 30.0, 1.3
df = df.sort_index().reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

(假设索引是提供的,从1开始)

  • 这有点疯狂 (3认同)