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

筛选高蛋白前15行并按calories排序,解决NoneType属性错误

问题解决方法

错误原因

当你使用sort_values(..., inplace=True)时,该方法会直接修改原df对象,返回值为None,因此df1被赋值为None,调用df1.head()就会触发AttributeError: 'NoneType' object has no attribute 'head'。

正确实现代码

你的需求是先按protein降序筛选前15行高蛋白数据,再将这15行按calories排序(升/降序可选),保留结果并删除其余数据。推荐用链式操作完成,清晰且避免inplace的坑:

# 按protein降序取前15行,再按calories升序排序,结果存到新变量
df_high_protein = df.sort_values(by='protein', ascending=False).head(15).sort_values(by='calories', ascending=True)

# 若要直接覆盖原DataFrame,执行以下代码
# df = df.sort_values(by='protein', ascending=False).head(15).sort_values(by='calories', ascending=True)

如果需要按calories降序排列,只需把最后一个参数ascending=True改为ascending=False。

额外说明

尽量避免使用inplace=True:它会直接修改原数据,不利于调试和数据回溯;链式操作更直观,还能避免因返回None导致的属性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:15:30