-1

I have a pandas df like this

id v1 v2 v3 v4
1  a  a  b  b 
2  x  f  f  a

How can I order it with a based on values from a set such as

setorder = ('1','3','2','4')

yields

id v1 v3 v2 v4
1  a  b  a  b 
2  x  f  f  a

Thanks

petezurich
  • 9,280
  • 9
  • 43
  • 57
EGM8686
  • 1,492
  • 1
  • 11
  • 22
  • 3
    Possibly a duplicate question https://stackoverflow.com/q/13148429/1328439 – Dima Chubarov Jul 19 '22 at 05:58
  • 2
    First of all, set is a collection which is unordered. Instead you'll have to use tuple or list. And also without trying by yourself asking for a solution directly is not a good practice here on stackoverflow. Kindly refrain doing this in the future. – Tony Montana Jul 19 '22 at 06:00

2 Answers2

2

Set is not ordered, so is possible use tuple like in sample data:

tupleorder = ('1','3','2','4')

df1 = df[['id'] + [f'v{x}' for x in tupleorder]]
print (df1)
   id v1 v3 v2 v4
0   1  a  b  a  b
1   2  x  f  f  a
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

Try this:

cols = ('1','3','2','4')
cols = [f"v{x}" for x in cols]
df[cols]

Print out:

    v1  v3  v2  v4
0   a   b   a   b
1   x   f   f   a

You alternatively can use a list for cols which is ordered as well.

petezurich
  • 9,280
  • 9
  • 43
  • 57