将给定行移动到DataFrame的末尾 [英] Move given row to end of DataFrame

查看:182
本文介绍了将给定行移动到DataFrame的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从DataFrame中获取一行,并将其添加到同一个DataFrame中。

I would like to take a given row from a DataFrame and prepend or append to the same DataFrame.

我的下面的代码只是这样,但我不知道我是正确的方式,还是有一个更简单,更好,更快的方式? / p>

My code below does just that, but I'm not sure if I'm doing it the right way or if there is an easier, better, faster way?

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)

谢谢

推荐答案

而不是concat我只会直接分配给df后 shift ,然后使用 iloc 来引用您要分配行的位置,则必须调用 squeeze ,以便指定只是值并失去原始的索引值,否则会引发一个 ValueError

Rather than concat I would just assign directly to the df after shifting, then use iloc to reference the position you want to assign the row, you have to call squeeze so that you assign just the values and lose the original index value otherwise it'll raise a 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

这篇关于将给定行移动到DataFrame的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆