首页 > 解决方案 > df.sort_values 不是排序表(python/pandas)

问题描述

pandas 中的 df.sort_values 对我不起作用,相同的 df 未经排序就返回。

def findExpression(transType, sortColName=None):
    global df

    if transType == 'sortAscending':
        df.sort_values(sortColName)
        return df

print(findExpression('sortAscending', sortColName='col9'))

Actual Output:
    col1  col2        col3        col4      col5  col6   col7   col8  col9
0  12345  12ab  2008-11-22  2009-11-22     beans  25.0  715.0   True    10
1  67890  34cd  2009-12-23  2010-12-23  catzilla  25.0   75.0  False     6
2  13579  56ef  2010-01-24  2011-01-24     boots  25.0   75.0   True     5
3  24680  78gh  2011-02-25  2012-02-25   whitish  25.0   75.0   True     6
4  12560  90ij  2012-03-26  2013-03-26      coco  25.0   75.0   True     1

Expected:
    col1  col2        col3        col4      col5  col6   col7   col8  col9
0  12560  90ij  2012-03-26  2013-03-26      coco  25.0   75.0   True     1
1  13579  56ef  2010-01-24  2011-01-24     boots  25.0   75.0   True     5
2  24680  78gh  2011-02-25  2012-02-25   whitish  25.0   75.0   True     6
3  67890  34cd  2009-12-23  2010-12-23  catzilla  25.0   75.0  False     6
4  12345  12ab  2008-11-22  2009-11-22     beans  25.0  715.0   True    10

标签: pythonpandascsvsorting

解决方案


大多数 pandas 函数不会直接修改元素,而是返回其修改后的副本。如果要直接修改对象,则必须添加选项inplace = True

df.sort_values(sortColName, inplace = True)

这与执行以下操作相同:

df = df.sort_values(sortColName)

推荐阅读