我会直接分配给 df 之后,而不是 concatshift http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html#pandas.DataFrame.shifting,然后使用iloc
要引用要分配行的位置,您必须调用squeeze
这样您只需分配值并丢失原始索引值,否则会引发ValueError
:
In [210]:
df = pd.DataFrame({'a':np.arange(5)})
df
Out[210]:
a
0 0
1 1
2 2
3 3
4 4
In [206]:
target_row = df.ix[[2],:]
target_row
Out[206]:
a
2 2
In [211]:
df = df.shift()
df.iloc[0] = target_row.squeeze()
df
Out[211]:
a
0 2
1 0
2 1
3 2
4 3
EDIT
要在末尾插入:
In [255]:
df = pd.DataFrame({'a':np.arange(5)})
target_row = df.ix[[2],:]
df = df.shift(-1)
df.iloc[-1] = target_row.squeeze()
df
Out[255]:
a
0 1
1 2
2 3
3 4
4 2
另一个更新
感谢@AsheKetchum 指出我之前的答案是不正确的,现在看到这个 3 年后我意识到你可以reindex
原来的df:
如果我们将索引的副本作为list
:
In[24]:
idx = df.index.tolist()
idx
Out[24]: [0, 1, 2, 3, 4]
那么我们就可以pop
此列表中感兴趣的索引:
In[25]:
idx.pop(2)
idx
Out[25]: [0, 1, 3, 4]
现在我们可以reindex
通过添加到此列表:
In[26]:
df.reindex([2] + idx)
Out[26]:
a
2 2
0 0
1 1
3 3
4 4
或附加:
In[27]:
df.reindex(idx+[2])
Out[27]:
a
0 0
1 1
3 3
4 4
2 2