如何使用多列中的值排序 pandas 数据框? [英] How to sort pandas data frame using values from several columns?

查看:128
本文介绍了如何使用多列中的值排序 pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

  df = pandas.DataFrame([{'c1':3,'c2 ':10},{'c1':2,'c2':30},{'c1':1,'c2':20},{'c1':2,'c2':15},{'c1 ':2,'c2':100}])

或者以人类可读的形式: p>

  c1 c2 
0 3 10
1 2 30
2 1 20
3 2 15
4 2 100

以下排序命令的工作原理如下:

  df.sort(['c1','c2'],ascending = False)

输出:

  c1 c2 
0 3 10
4 2 100
1 2 30
3 2 15
2 1 20

但是以下命令:

  df.sort(['c1','c2 '],ascending = [False,True])

结果

  c1 c2 
2 1 20
3 2 15
1 2 30
4 2 100
0 3 10

这不是我期望的。我希望将第一列中的值从最大到最小排序,如果第一列中的值相同,则按第二列的升序值排序。



<有没有人知道为什么它不按预期工作?



ADDED



这是复制粘贴:

 >>> df.sort(['c1','c2'],ascending = [False,True])
c1 c2
2 1 20
3 2 15
1 2 30
4 2 100
0 3 10


解决方案

p>您的代码适用于我。

 >>>进口大熊猫
>>> df = pandas.DataFrame([{'c1':3,'c2':10},{'c1':2,'c2':30},{'c1':1,'c2':20},{ 'c1':2,'c2':15},{'c1':2,'c2':100}])
>>> df.sort(['c1','c2'],ascending = [False,True])
c1 c2
0 3 10
3 2 15
1 2 30
4 2 100
2 1 20






您是否按原样粘贴?

 >>> df.sort(['c1','c2'],ascending = [True,True])
c1 c2
2 1 20
3 2 15
1 2 30
4 2 100
0 3 10


I have the following data frame:

df = pandas.DataFrame([{'c1':3,'c2':10},{'c1':2, 'c2':30},{'c1':1,'c2':20},{'c1':2,'c2':15},{'c1':2,'c2':100}])

Or, in human readable form:

   c1   c2
0   3   10
1   2   30
2   1   20
3   2   15
4   2  100

The following sorting-command works as expected:

df.sort(['c1','c2'], ascending=False)

Output:

   c1   c2
0   3   10
4   2  100
1   2   30
3   2   15
2   1   20

But the following command:

df.sort(['c1','c2'], ascending=[False,True])

results in

   c1   c2
2   1   20
3   2   15
1   2   30
4   2  100
0   3   10

and this is not what I expect. I expect to have the values in the first column ordered from largest to smallest, and if there are identical values in the first column, order by the ascending values from the second column.

Does anybody know why it does not work as expected?

ADDED

This is copy-paste:

>>> df.sort(['c1','c2'], ascending=[False,True])
   c1   c2
2   1   20
3   2   15
1   2   30
4   2  100
0   3   10

解决方案

Your code works for me.

>>> import pandas
>>> df = pandas.DataFrame([{'c1':3,'c2':10},{'c1':2, 'c2':30},{'c1':1,'c2':20},{'c1':2,'c2':15},{'c1':2,'c2':100}])
>>> df.sort(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20


Did you paste as is?

>>> df.sort(['c1','c2'], ascending=[True,True])
   c1   c2
2   1   20
3   2   15
1   2   30
4   2  100
0   3   10

这篇关于如何使用多列中的值排序 pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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