2013-04-08 23 views
22

我有類似下面這樣的數據框對象:是否可以使用熊貓在數據框中的任意位置插入一行?

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

我想要做的是通過一些指標值指定的位置插入一行,並相應更新以下指標。例如:

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

什麼是最好的方法來做到這一點?

回答

25

你可以切片並使用concat來獲得你想要的。

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

這將在您的示例輸出中產生數據幀。據我所知,concat是在熊貓中實現插入類型操作的最佳方法,但我承認我絕不是熊貓專家。

+0

@bdiamante嗨,請看看這個問題在這裏https://stackoverflow.com/questions/44599589/inserting-new-rows-in-pandas-data-frame-at-specific-indices – Liza 2017-06-21 21:53:59