You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决df.sort_values()执行时出现的KeyError问题?

问题:DataFrame排序触发KeyError

我始终无法找到这个特定错误的解决方案。我尝试对DataFrame执行简单排序,但每次操作都会触发KeyError。

代码如下:

import numpy as np
import pandas as pd

scores = [97, 91, 95, 88, 67, 65]
weights = [.5, .2, .1, .1, .05, .05]

##Put this into a DataFrame
df = pd.DataFrame(columns = ['Scores','Weights'])
df.Scores = scores
df.Weights = weights

df.sort_values(df['Scores'])

每次运行都会得到如下报错:

KeyError: 0 97
1 91
2 95
3 88
4 67
5 65
Name: Scores, dtype: int64

解决方案

问题出在sort_values的参数使用上——你传入的是df['Scores'](一个Series对象),但这个方法需要的是列名的字符串(或列名字符串列表)。当你传入Series时,pandas会错误地将这个Series的内容当作要查找的列名,自然找不到对应列,因此抛出KeyError。

正确代码示例

  1. 直接传入列名字符串,返回排序后的新DataFrame(原DataFrame不变):
sorted_df = df.sort_values('Scores')
  1. 显式指定by参数(代码可读性更强):
sorted_df = df.sort_values(by='Scores')
  1. 如果要直接修改原DataFrame,添加inplace=True参数:
df.sort_values(by='Scores', inplace=True)

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:14