pandas 将所需的行移动到熊猫数据框的顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38980507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving desired row to the top of pandas Data Frame
提问by ropolo
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?
在 中pandas
,如何在不创建数据框副本的情况下将行复制或移动到数据框的顶部?
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
回答by Kartik
回答by Merlin
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
Basically, since you cant insert into index at 0, create a column so you can.
基本上,由于您不能在 0 处插入索引,因此可以创建一列。
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
回答by ropolo
Okay, I think I came up with a solution. By all means, please feel free to add your own answer if you think yours is better:
好吧,我想我想出了一个解决方案。无论如何,如果您认为自己的答案更好,请随时添加您自己的答案:
import numpy as np
df.ix[3] = np.nan
df
Probe Sequence
0 Test1 AATGCGT
1 Test2 TGCGTAA
2 Test3 ATGCATG
3 NaN NaN
df = df.shift(1)
Probe Sequence
0 NaN NaN
1 Test1 AATGCGT
2 Test2 TGCGTAA
3 Test3 ATGCATG
df.ix[0] = df.ix[2]
df
Probe Sequence
0 Test3 ATGCATG
1 Test1 AATGCGT
2 Test2 TGCGTAA
3 Test3 ATGCATG