python - 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
解决方案
大多数 pandas 函数不会直接修改元素,而是返回其修改后的副本。如果要直接修改对象,则必须添加选项inplace = True
:
df.sort_values(sortColName, inplace = True)
这与执行以下操作相同:
df = df.sort_values(sortColName)
推荐阅读
- windows - 为什么 Linux git 在 Windows WSL 中运行并在 NTFS 文件系统上运行时不创建正确的 Windows 符号链接?
- ios - SwiftUI 中无法使用对象属性创建颜色
- kotlin - 如何使用 ArchUnit 在 Kotlin 的构造函数中强制执行私有参数?
- batch-file - 用增加的数字替换文件名以稍后恢复的批处理脚本
- mysql - 比较两个表列
- python - 如何访问另一个类的实例中保存的类实例中的属性?
- google-apps-script - 使 onEdit() 更快更高效
- python-3.x - 多变量回归模型成本不降低
- python - 确保总有一个平台供玩家跳跃
- grammar - 如何在 Raku 中使用匹配分隔符