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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15888648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:17:23  来源:igfitidea点击:

Is it possible to insert a row at an arbitrary position in a dataframe using pandas?

pythonpandas

提问by Troas

I have a DataFrame object similar to this one:

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

       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?

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

采纳答案by bdiamante

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

你可以切片并使用 concat 来获得你想要的。

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

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.

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

回答by Reimar

I find it more readable to sort rather than slice and concatenate.

我发现排序而不是切片和连接更具可读性。

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)

回答by anurag pandey

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

this solution is replacing that index values i want to just add one index without replacing the index values.

此解决方案正在替换该索引值,我只想添加一个索引而不替换索引值。