I am new in Python and try to replace rows.
I have a dataframe such as:
X | Y |
---|---|
1 | a |
2 | d |
3 | c |
4 | a |
5 | b |
6 | e |
7 | a |
8 | b |
I have two question:
1- How can I replace 2nd row with 5th, such as:
X | Y |
---|---|
1 | a |
5 | b |
3 | c |
4 | a |
2 | d |
6 | e |
7 | a |
8 | b |
2- How can I put 6th row above 3rd row, such as:
X | Y |
---|---|
1 | a |
2 | d |
6 | e |
3 | c |
4 | a |
5 | b |
7 | a |
8 | b |
CodePudding user response:
First use DataFrame.iloc
, python counts from 0
, so for select second row use 1
and for fifth use 4
:
df.iloc[[1, 4]] = df.iloc[[4, 1]]
print (df)
X Y
0 1 a
1 5 b
2 3 c
3 4 a
4 2 d
5 6 e
6 7 a
7 8 b
And then rename
indices for above value, here 1
and sorting with only stable sorting mergesort
:
df = df.rename({5:1}).sort_index(kind='mergesort', ignore_index=True)
print (df)
X Y
0 1 a
1 2 d
2 6 e
3 3 c
4 4 a
5 5 b
6 7 a
7 8 b