pandas 如何按行对数据框进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38941735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:49:20  来源:igfitidea点击:

How to sort dataframe by a row?

pythonpandasdataframe

提问by yensheng

I have a dataframe:

我有一个数据框:

import pandas as pd

df = pd.DataFrame(data={'x':[7,1,9], 'y':[4,5,6],'z':[1,8,3]}, index=['a', 'b', 'c'])

It shows:

表明:

enter image description here

在此处输入图片说明

How to sort this dataframe by row['a']: After sort the dataframe, it might be:

How to sort this dataframe by row['a']: 对数据框进行排序后,它可能是:

enter image description here

在此处输入图片说明

回答by unutbu

In [7]: df.iloc[:, np.argsort(df.loc['a'])]
Out[7]: 
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9


np.argsortreturns the indices one would use to sort the arow, df.loc['a']:

np.argsort返回用于对a行进行排序的索引df.loc['a']

In [6]: np.argsort(df.loc['a'])
Out[6]: 
x    2
y    1
z    0
Name: a, dtype: int64

Once you have those indices, you can use them to reorder the columns of df(by using df.iloc).

一旦你有了这些索引,你就可以使用它们来重新排序df(通过使用df.iloc)的列。

回答by taras

You can use reindex_axismethod:

您可以使用reindex_axis方法:

>>> df.reindex_axis(sorted(df.columns, key=lambda x: df[x]['a']), axis=1)
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9

回答by DeepSpace

You can use axis=1when calling sort:

您可以axis=1在调用时使用sort

df.sort(axis=1, ascending=False)   

>>       z  y  x
      a  1  4  7
      b  8  5  1
      c  3  6  9

Note that sortis not inplace by default, so either reassign its return value or use inplace=True.

请注意,sort默认情况下它不是就地,因此要么重新分配其返回值,要么使用inplace=True.

回答by ayhan

In v0.19 you can sort by rows:

在 v0.19 中,您可以按行排序:

pd.__version__
Out: '0.19.0rc1'

df.sort_values(by='a', axis=1)
Out: 
   z  y  x
a  1  4  7
b  8  5  1
c  3  6  9