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

查看:66
本文介绍了是否可以使用 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
...

做到这一点的最佳方法是什么?

What would be the best way to do this?

推荐答案

您可以切片并使用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是在熊猫中实现插入类型操作的最佳方法,但是请记住,我绝不是熊猫专家.

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天全站免登陆