如何按两列或更多列对python pandas中的dataFrame进行排序?

问题:如何按两列或更多列对python pandas中的dataFrame进行排序?

假设我有一个数据列a,其中包含,bc,我想b按升序按列对数据帧进行排序,然后按c降序按列对数据帧进行排序,我该怎么做?

Suppose I have a dataframe with columns a, b and c, I want to sort the dataframe by column b in ascending order, and by column c in descending order, how do I do this?


回答 0

从0.17.0版本开始,sort不推荐使用该方法,而推荐使用sort_valuessort在0.20.0版本中被完全删除。参数(和结果)保持不变:

df.sort_values(['a', 'b'], ascending=[True, False])

您可以使用的升序参数sort

df.sort(['a', 'b'], ascending=[True, False])

例如:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

正如@renadeen所评论

默认情况下,排序不正确!因此,您应该将sort方法的结果分配给变量,或者将inplace = True添加到方法调用中。

也就是说,如果您想将df1用作已排序的DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

要么

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn’t in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

回答 1

从熊猫0.17.0开始,DataFrame.sort()已弃用该熊猫,并将其设置为在以后的熊猫版本中将其删除。现在,按值对数据框进行排序的方法是DataFrame.sort_values

因此,您问题的答案现在是

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

回答 2

对于数字数据的大型数据框,您可能会通过看到显着的性能改进numpy.lexsort,该方法使用一系列键执行间接排序:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

一个特殊之处是定义的排序顺序numpy.lexsort颠倒了:首先(-'b', 'a')按系列排序a。我们否定级数b以反映我们希望该级数降序排列。

请注意,np.lexsort仅使用数字值排序,而同时pd.DataFrame.sort_values使用字符串或数字值。np.lexsort与字符串一起使用将给出:TypeError: bad operand type for unary -: 'str'

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.