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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With