M.A
M.A

Reputation: 65

Re-arrange rows values

I have 100 columns and 200 rows. Each value contains "First", "Second", "King", or "Queen" concatenate with other random string and separated by _. Note: All of these are concatenated with other values. Every row has "First" once, but others can be multiple.

Below is an example:

enter image description here

I want to re-arrange the values of each row as per my conditions:

Desired output:

I tried to do a for loop to iterate each row but I don't know how to switch values or replace like my requirement.

enter image description here

Upvotes: 5

Views: 66

Answers (1)

anky
anky

Reputation: 75140

Try with:

l=['First','Second','King','Queen']
d=dict(zip(l,range(len(l))))
#{'First': 0, 'Second': 1, 'King': 2, 'Queen': 3}
df=pd.DataFrame(np.sort(df.replace(d),axis=1),columns=df.columns,
                index=df.index).replace({v:k for k,v in d.items()})
print(df)

         A       B       C     ETC
1    First  Second  Second  Second
2    First  Second  Second    King
3    First  Second    King   Queen
ETC  First  Second  Second    King

Upvotes: 2

Related Questions