如何在pandas DataFrame中插入新行并将下方索引向下移动+1

0 投票
2 回答
1629 浏览
提问于 2025-04-18 08:29

我有一个 pandas 的数据表(DataFrame)

In [103]: df=pd.DataFrame({'A': [3,4,7,5], 'B': [6,1,3,6]})

In [104]: df
Out[104]: 
   A  B
0  3  6
1  4  1
2  7  3
3  5  6
[4 rows x 2 columns]

我想在索引为 2 的位置插入一行,A 的值为 9,B 的值也为 9,并且把下面的行的索引都往下移动 1。最后的结果是

In [114]: df
Out[114]: 
   A  B
0  3  6
1  4  1
2  9  9
3  7  3
4  5  6
[5 rows x 2 columns]

2 个回答

1

我觉得这个方法挺有意思的:

df=pd.DataFrame({'A': [3,4,7,5], 'B': [6,1,3,6]})
x = len(df.index)
for item in df.index:
    if x > 2:
        df.ix[x] = df.ix[x-1]
    x = x-1
df.ix[2] = 9
3

可能还有更有效的方法,但这里有一种做法——在你想插入值的地方,先把前面和后面的部分切出来,然后用pd.concat把它们拼接在一起。

In[1] pd.concat([df.loc[0:1],  pd.DataFrame({'A':9, 'B':9}, index=[0]), df.loc[2:]], ignore_index=True)

Out[92]: 
   A  B
0  3  6
1  4  1
2  9  9
3  7  3
4  5  6

撰写回答