在列和索引的值上对Pandas DataFrame进行排序? [英] Sort pandas dataframe both on values of a column and index?

查看:238
本文介绍了在列和索引的值上对Pandas DataFrame进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过列的值和索引对pandas数据框进行排序是否可行?

Is it feasible to sort pandas dataframe by values of a column, but also by index?

如果按列的值对pandas数据框进行排序,则可以按列对得到的数据框进行排序,但是不幸的是,在相同的列值内,您看到的数据框索引的顺序杂乱无章.

If you sort a pandas dataframe by values of a column, you can get the resultant dataframe sorted by the column, but unfortunately, you see the order of your dataframe's index messy within the same value of a sorted column.

因此,我可以按列对数据框进行排序,例如名为count的列,还可以按index的值对其进行排序吗?并且,按降序对列进行排序,而按升序对索引进行排序也是可行的吗?

So, can I sort a dataframe by a column, such as the column named count but also sort it by the value of index? And is it also feasible to sort a column by descending order, but whereas sort a index by ascending order?

我知道如何对数据帧中的多个列进行排序,也知道我可以通过首先对索引进行reset_index()并对其进行排序,然后再次创建索引来实现我的要求.但这是更直观,更有效的方法吗?

I know how to sort multiple columns in dataframe, and also know I can achieve what I'm asking here by first reset_index() the index and sort it, and then create the index again. But is it more intuitive and efficient way to do it?

推荐答案

Pandas 0.23 最终使您到达那里:-D

Pandas 0.23 finally gets you there :-D

您现在可以将索引名称(不仅是列名称)作为参数传递给sort_values.因此,这种单线工作原理:

You can now pass index names (and not only column names) as parameters to sort_values. So, this one-liner works:

df = df.sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])

如果您的索引当前未命名:

And if your index is currently unnamed:

df = df.rename_axis('MyIdx').sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True])

这篇关于在列和索引的值上对Pandas DataFrame进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆