Ernesto Lopez Fune
Ernesto Lopez Fune

Reputation: 583

Sorting a dataframe by another

I have an initial dataframe X:

   x  y  z  w
0  1  a  b  c
1  1  d  e  f
2  0  g  h  i
3  0  k  l  m
4 -1  n  o  p
5 -1  q  r  s
6 -1  t  v  à

with many columns and rows (this is a toy example). After applying some Machine Learning procedures, I get back a similar dataframe, but with the -1s changed to 0s or 1s and the rows sorted in a different way; for example:

   x  y  z  w
4  1  n  o  p
0  1  a  b  c
6  0  t  v  à
1  1  d  e  f
2  0  g  h  i
5  0  q  r  s
3  0  k  l  m

How could I do in order to sort the second dataframe as the first one? For example, like

   x  y  z  w
0  1  a  b  c
1  1  d  e  f
2  0  g  h  i
3  0  k  l  m
4  1  n  o  p
5  0  q  r  s
6  0  t  v  à

Upvotes: 0

Views: 43

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 30971

Use:

df.sort_index(inplace=True)

It restores the order, just by index

Upvotes: 0

rafaelc
rafaelc

Reputation: 59274

If you can't trust just sorting the indexes (e.g. if the first df's indexes are not sorted, or if you have something other than RangeIndex), just use loc

df2.loc[df.index]

   x  y  z  w
0  1  a  b  c
1  1  d  e  f
2  0  g  h  i
3  0  k  l  m
4  1  n  o  p
5  0  q  r  s
6  0  t  v  à

Upvotes: 1

Related Questions