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

用Dask、Pandas IntervalIndex匹配薪资区间报InvalidIndexError的原因?

InvalidIndexError报错原因
  • 核心原因:pandas.IntervalIndex.get_loc() 方法仅支持接收单个标量值查询所属区间,你在map_partitions的回调函数中传入的参数x是对应分区的Salary整列数据(pandas Series类型),接口入参类型不匹配直接触发索引错误。
  • 具体表现:报错日志里的key值为0 10000,这是带行索引的Series对象,不是你预期的10000这个单独数值,get_loc无法识别Series类型的查询键。

修复方案

你可以对Series的每个元素单独执行区间匹配,修改后的代码示例如下:

import dask.dataframe as dd
import pandas as pd

salary_df = pd.DataFrame({"Salary":[10000, 50000, 25000, 30000, 7000, 100000]})
salary_category = pd.DataFrame({"Hi":[5000, 20000, 25000, 30000, 90000, 120000],
                        "Low":[0,  5001, 20001, 25001, 30001, 90001],
                        "category":["Very Poor", "Poor", "Medium", "Rich", "Super Rich", "Ultra Rich" ]
                        })
sal_ddf = dd.from_pandas(salary_df, npartitions=10)
salary_category.index = pd.IntervalIndex.from_arrays(salary_category['Low'],salary_category['Hi'],closed='both')

# 修改map_partitions内的逻辑,对Series每个元素单独匹配
sal_ddf['Category'] = sal_ddf['Salary'].map_partitions(
    lambda x: x.apply(lambda val: salary_category.iloc[salary_category.index.get_loc(val)]['category']), 
    meta=('Category', 'str')
)

print(salary_category)
print(sal_ddf.compute())

内容的提问来源于stack exchange,提问作者jhon.smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:57:00