d_frEak
d_frEak

Reputation: 470

Sorting values between column using pandas

Assume I have this simple dataframe

matrix = [(222, 16, 23),
          (333, 31, 51),
          (4, 34, 11),
          ]
df = pd.DataFrame(matrix, index=list('abc'), columns=list('xyz'))

enter image description here

I want to order by the value ignoring the columns like this

enter image description here

Right now I am using the swapping idea in pandas from this link and doing brute force sort

df.loc[df['x']>df['y'],['x','y']] = df.loc[df['x']>df['y'],['y','x']].values
df.loc[df['x']>df['z'],['x','z']] = df.loc[df['x']>df['z'],['z','x']].values
df.loc[df['y']>df['z'],['y','z']] = df.loc[df['y']>df['z'],['z','y']].values

It is working but actually I have more columns than 3, and I will be grateful if someone can give me another idea to sort this data, thank you

Upvotes: 1

Views: 124

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

You can use np.sort over axis 1 here:

# df
#      x   y   z
# a  222  16  23
# b  333  31  51
# c    4  34  11

df = pd.DataFrame(np.sort(df.values, axis=1),
                  columns=df.columns,
                  index=df.index)

    x   y    z
a  16  23  222
b  31  51  333
c   4  11   34

Upvotes: 2

anon01
anon01

Reputation: 11171

This is a bit of a strange request - usually the columns contain semantic meaning. You can do it via:

cols = df.columns
df = pd.DataFrame(np.sort(df.values, axis=1), columns=cols, index=df.index)

output:

    x   y    z
a  16  23  222
b  31  51  333
c  4  11    34

Upvotes: 2

Related Questions