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?
提问by yensheng
回答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.argsort
returns the indices one would use to sort the a
row, 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_axis
method:
您可以使用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
回答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