-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

2
  • 3
    Possibly a duplicate question stackoverflow.com/q/13148429/1328439 Commented Jul 19, 2022 at 5: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. Commented Jul 19, 2022 at 6:00

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.