是否可以使用 Pandas 在数据框中的任意位置插入一行? [英] Is it possible to insert a row at an arbitrary position in a dataframe using pandas?

查看:32
本文介绍了是否可以使用 Pandas 在数据框中的任意位置插入一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataFrame object similar to this one:

       onset    length
1      2.215    1.3
2     23.107    1.3
3     41.815    1.3
4     61.606    1.3
...

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

What I would like to do is insert a row at a position specified by some index value and update the following indices accordingly. E.g.:

       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
...

最好的方法是什么?

推荐答案

你可以切片并使用 concat 来得到你想要的.

You could slice and use concat to get what you want.

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

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

This will produce the dataframe in your example output. As far as I'm aware, concat is the best method to achieve an insert type operation in pandas, but admittedly I'm by no means a pandas expert.

这篇关于是否可以使用 Pandas 在数据框中的任意位置插入一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆