Moving Desired Row To The Top Of Pandas Data Frame
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,
Solution 1:
Try this. You don't need to make a copy of the 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 can't insert the row into the index at 0, create a column so you can.
If you want the 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
Edit: df.ix
is deprecated. Here's the same method with .loc
.
df["new"] = range(1,len(df)+1)
df.loc[df.index==2, 'new'] = 0
df.sort_values("new").drop('new', axis=1)
Solution 2:
df = pd.concat([df.iloc[[n],:], df.drop(n, axis=0)], axis=0)
Solution 3:
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
Post a Comment for "Moving Desired Row To The Top Of Pandas Data Frame"