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"
执行后得到的结果符合预期:
| 索引 | Expense | Proportion |
|---|---|---|
| 0 | Salaries | 0.62 |
| 1 | Advertising | 0.15 |
| 2 | Office Rent | 0.15 |
| 3 | Other | 0.03 |
| 4 | Other | 0.03 |
| 5 | Other | 0.01 |
| 6 | Other | 0.01 |
如果习惯用序列方法,也可以用mask实现等价效果:
expense_overview["Expense"] = expense_overview["Expense"].mask( cond=expense_overview["Proportion"] < 0.05, other="Other" )
内容的提问来源于stack exchange,提问作者Corazu
相关产品推荐
相关产品推荐

