将所需的行移到 pandas 数据框的顶部 [英] Moving desired row to the top of pandas Data Frame

查看:54
本文介绍了将所需的行移到 pandas 数据框的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pandas中,如何在不创建数据框副本的情况下将行复制或移动到数据框顶部?

In pandas, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame?

例如,我设法用下面的代码完成了我想做的事,但我印象中可能会有更好的方法来完成此任务:

For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this:

import pandas as pd

df = pd.DataFrame({'Probe':['Test1','Test2','Test3'], 'Sequence':['AATGCGT','TGCGTAA','ATGCATG']})

df

   Probe Sequence
0  Test1  AATGCGT
1  Test2  TGCGTAA
2  Test3  ATGCATG

df_shifted = df.shift(1)

df_shifted

   Probe Sequence
0    NaN      NaN
1  Test1  AATGCGT
2  Test2  TGCGTAA


df_shifted.ix[0] = df.ix[2]

df_shifted

   Probe Sequence
0  Test3  ATGCATG
1  Test1  AATGCGT
2  Test2  TGCGTAA

推荐答案

尝试一下,您不是在复制数据框,

Try this, You are not making a copy of dataframe,:

df["new"] = range(1,len(df)+1)

   Probe Sequence  new
0  Test1  AATGCGT    1
1  Test2  TGCGTAA    2
2  Test3  ATGCATG    3


df.ix[2,'new'] = 0
df.sort_values("new").drop('new', axis=1)

   Probe Sequence
2  Test3  ATGCATG
0  Test1  AATGCGT
1  Test2  TGCGTAA

基本上,由于您不能在索引0处插入索引,因此可以创建一列.

Basically, since you cant insert into index at 0, create a column so you can.

如果要排序索引,请使用此:

If you want index ordered, use this:

df.sort_values("new").reset_index(drop='True').drop('new', axis=1)

   Probe Sequence
0  Test3  ATGCATG
1  Test1  AATGCGT
2  Test2  TGCGTAA

这篇关于将所需的行移到 pandas 数据框的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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