ropolo ropolo - 3 months ago 24
Python Question

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, 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

Answer

pandas.concat:

pd.concat([df.iloc[[n],:], df.drop(n, axis=0)], axis=0)
Comments