使用mypy检查pandas的to_dict方法时,如何指定索引键为整数类型?
解决Pandas+Mypy类型不兼容:指定索引键为整数类型
问题场景
我写了一段简化的Pandas代码,把year列设为索引后转成字典,用Mypy检查时出现了类型错误:
import pandas as pd from typing import Dict df = pd.DataFrame( {"year": [2024, 2025], "my_output": [1, 2], "foo": ["a", "b"]} ) df.set_index("year", inplace=True) row_dict = df.to_dict("index") ouput_dict: Dict[int, int] = { key: val["my_output"] for key, val in row_dict.items() }
Mypy报错
Key expression in dictionary comprehension has incompatible type "Hashable"; expected type "int"
解决办法
1. 用类型断言明确键的类型
通过typing.cast直接告诉Mypy字典的键是整数类型,这是最直接的方式:
from typing import cast, Dict # ... 前面代码不变 ... ouput_dict: Dict[int, int] = { cast(int, key): val["my_output"] for key, val in row_dict.items() }
如果担心运行时类型不符,还可以加个判断兜底:
ouput_dict: Dict[int, int] = { cast(int, key): val["my_output"] for key, val in row_dict.items() if isinstance(key, int) }
2. 显式处理索引类型
设置索引时避免用inplace=True(会干扰Mypy的类型推断),改用返回新DataFrame的方式,再显式确认索引类型:
# 不用inplace,返回新DataFrame,类型推断更准确 df = df.set_index("year") # 显式转换索引为整数类型,给Mypy明确提示 df.index = df.index.astype(int) row_dict = df.to_dict("index") ouput_dict: Dict[int, int] = { key: val["my_output"] for key, val in row_dict.items() }
3. 用TypedDict定义行结构(更严谨)
如果需要更清晰的类型约束,可以用TypedDict定义每一行的结构,再配合类型断言:
from typing import TypedDict, cast, Dict class RowData(TypedDict): my_output: int foo: str # ... 前面代码不变 ... # 断言row_dict的键是int,值是RowData类型 row_dict: Dict[int, RowData] = cast(Dict[int, RowData], df.to_dict("index")) ouput_dict: Dict[int, int] = { key: val["my_output"] for key, val in row_dict.items() }
报错原因
Pandas的set_index方法返回的索引,在Mypy眼里默认是Hashable类型(所有可哈希类型的父类),它没法自动推断出你用的是整数列当索引,所以得手动给它明确类型。
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

