1

I am trying to sort each row of a DataFrame element wise.

Input:

    A   B   C
0   10  5   6
1   3   6   5
2   1   2   3

Output:

    A   B   C
0   10  6   5
1   6   5   3
2   3   2   1

It feels this should be easy but I've been failing for while... Very much a beginner in Python.

1 Answer 1

1

Use np.sort with swap ordering by indexing:

df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1], 
                   index=df.index, 
                   columns=df.columns)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1

Pandas solution, slowier, is apply sorting for each row separately, convert to array and then to Series:

f = lambda x: pd.Series(x.sort_values(ascending=False).to_numpy(), index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1

If possible missing values for me working:

print (df)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN


df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1], 
                   index=df.index, 
                   columns=df.columns)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

In pandas is possible use na_position parameter for specify order of them:

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='first').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='last').to_numpy(), 
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN
Sign up to request clarification or add additional context in comments.

16 Comments

@Tikhon - there is used .to_numpy() ?
@Tikhon - there is typo, stocks.sort, need np.sort
@Tikhon - there are missing values, unfortunately. If sorting, missing values should be last? Or first?
@Tikhon - For me working if all values are numbers and missing values are NaNs
@Tikhon - Edited answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.