python - Sort all columns of a pandas DataFrame independently using sort_values() -
i have dataframe , want sort columns independently in descending or ascending order.
import pandas pd data = {'a': [5, 2, 3, 6], 'b': [7, 9, 1, 4], 'c': [1, 5, 4, 2]} df = pd.dataframe.from_dict(data) b c 0 5 7 1 1 2 9 5 2 3 1 4 3 6 4 2
when use sort_values() not work expected (to me) , sorts 1 column:
foo = df.sort_values(by=['a', 'b', 'c'], ascending=[false, false, false]) b c 3 6 4 2 0 5 7 1 2 3 1 4 1 2 9 5
i can desired result if use solution this answer applies lambda function:
bar = df.apply(lambda x: x.sort_values().values) print(bar) b c 0 2 1 1 1 3 4 2 2 5 7 4 3 6 9 5
but looks bit heavy-handed me.
what's happening in sort_values() example above , how can sort columns in dataframe in pandas-way without lambda function?
you can use numpy.sort
dataframe
constructor:
df1 = pd.dataframe(np.sort(df.values, axis=0), index=df.index, columns=df.columns) print (df1) b c 0 2 1 1 1 3 4 2 2 5 7 4 3 6 9 5
Comments
Post a Comment