Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a row in pandas dataframe which have unordered index to the first row?

I have a dataframe df like this:

index  col1 col2 col3
noun   1     1   1
verb   4     6   1
<s>    9     6   5
Adj    5     1   3  
<end>  0     0   0 

How to I move the row with index <s> to the first row, so I have something like this:

index  col1 col2 col3
<s>    9     6   5
noun   1     1   1
verb   4     6   1
Adj    5     1   3  
<end>  0     0   0 

Thanks before!

like image 782
Saber Alex Avatar asked Dec 14 '22 00:12

Saber Alex


2 Answers

You can use reindex by list where prepend value and remove it by drop from original index:

val = '<s>'
idx = [val] + df.index.drop(val).tolist()
print (idx)
['<s>', 'noun', 'verb', 'Adj', '<end>']

print (df.reindex(idx))

       col1  col2  col3
index                  
<s>       9     6     5
noun      1     1     1
verb      4     6     1
Adj       5     1     3
<end>     0     0     0
like image 96
jezrael Avatar answered Dec 16 '22 14:12

jezrael


pandas

Find the location of <s> and build a new positional ordering

p = df.index.get_loc('<s>')
df.iloc[[p] + [i for i in range(len(df)) if i != p]]

       col1  col2  col3
index                  
<s>       9     6     5
noun      1     1     1
verb      4     6     1
Adj       5     1     3
<end>     0     0     0

numpy

a = (df.index.values != '<s>').argsort(kind='mergesort')
pd.DataFrame(df.values[a], df.index.values[a], df.columns)

       col1  col2  col3
index                  
<s>       9     6     5
noun      1     1     1
verb      4     6     1
Adj       5     1     3
<end>     0     0     0

time test

enter image description here

like image 26
piRSquared Avatar answered Dec 16 '22 13:12

piRSquared