2015-06-19 216 views
1

我想从DataFrame中获取给定的行并将其前置或附加到同一个DataFrame。将给定的行移动到DataFrame的末尾

我的代码如下,但我不知道我是否以正确的方式做,或者如果有更简单,更好,更快的方式吗?

testdf = df.copy() 
#get row 
target_row = testdf.ix[[2],:] 
#del row from df 
testdf.drop([testdf.index[2]], axis=0, inplace=True) 
#concat original row to end or start of df 
newdf = pd.concat([testdf, target_row], axis=0) 

感谢

回答

3

不是CONCAT我只想直接分配到DF后shift ING,然后用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 

编辑

要插入底:

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 
2

我可以将其降低到一个班轮:

pd.concat([df.ix[0:1], df.ix[3:], df.ix[[2]]]) 

我没有看到你的代码和我之间的性能差异,但。据推测复制是最大的罪魁祸首。

1

为了提高性能,您可能需要考虑将要移动到DataFrame末尾的所有行的运行列表保留下来,然后在单个pd.concat操作中一次全部移动它们。

df = pd.DataFrame(np.random.rand(5, 3), columns=list('ABC')) 
target_rows = [1, 3, 4] 

a = df.iloc[[i for i in df.index if i not in target_rows], :] 
b = df.iloc[target_rows, :] 
>>> pd.concat([a, b]) 
      A   B   C 
0 0.818722 0.174153 0.522383 
2 0.581577 0.840306 0.985089 
1 0.645752 0.238476 0.670922 
3 0.198271 0.501911 0.954477 
4 0.965488 0.735559 0.701077 
-1

我只是放下一行并追加到最后。

df = pd.DataFrame({'a':np.arange(5)}) 
df.drop(2).append(df.ix[2]).reset_index(drop=True) # move 3rd row 
df.drop(df.head(2).index).append(df.head(2)).reset_index() # move first 2 rows 
+0

您可能想添加一点评论来解释您的答案。 –

相关问题