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

Pandas布尔索引赋值报mixed-types非np.nan值错误解决

错误产生原因
  • 你生成的mask是作用于整个DataFrame全列的布尔矩阵,逻辑上会同时匹配Expense(字符串类型)和Proportion(浮点数类型)两列的单元格,后续赋值操作会尝试把浮点类型的Proportion列也修改为字符串"Other"。
  • 当你对包含多种数据类型的DataFrame做跨列布尔原地赋值时,如果传入的值不是np.nan,pandas无法自动处理不同类型列的类型兼容问题,就会抛出Cannot do inplace boolean setting on mixed-types with a non np.nan value错误。
  • 就算不触发类型错误,这个全表匹配的逻辑也不符合需求:你只需要修改Expense列的值,完全不需要触碰Proportion列。
正确实现代码

优先使用pandas官方推荐的.loc索引器赋值,逻辑最清晰,也不会触发链式索引警告:

# 筛选Proportion小于0.05的行,仅对这些行的Expense列做赋值
expense_overview.loc[expense_overview["Proportion"] < 0.05, "Expense"] = "Other"

执行后得到的结果符合预期:

索引ExpenseProportion
0Salaries0.62
1Advertising0.15
2Office Rent0.15
3Other0.03
4Other0.03
5Other0.01
6Other0.01

如果习惯用序列方法,也可以用mask实现等价效果:

expense_overview["Expense"] = expense_overview["Expense"].mask(
    cond=expense_overview["Proportion"] < 0.05,
    other="Other"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 15:03:24