Polars报错‘Expr’对象无map_dict属性,求替代映射方法
Polars字典映射替代方案
你遇到的AttributeError是因为map_dict是Polars较新加入的API,如果你的Polars版本偏低,就会找不到这个方法。下面是两种可靠的替代实现方式:
方法一:使用replace(推荐,性能最优)
replace是Polars原生的向量化映射方法,支持字典匹配+默认值设置,和map_dict的功能完全一致,且兼容性更好:
import polars as pl country_code_dict = { "CA": "Canada", "DE": "Germany", "FR": "France", None: "Not specified", } df = pl.DataFrame( { "country_code": ["FR", None, "ES", "DE"], } ).with_row_count() # 用replace完成映射 result_df = df.with_columns( pl.col("country_code") .replace(country_code_dict, default="unknown") .alias("remapped") ) print(result_df)
方法二:使用map_elements(适合复杂逻辑)
如果需要更灵活的自定义映射逻辑,可以用map_elements逐元素处理:
import polars as pl country_code_dict = { "CA": "Canada", "DE": "Germany", "FR": "France", None: "Not specified", } df = pl.DataFrame( { "country_code": ["FR", None, "ES", "DE"], } ).with_row_count() # 定义映射函数 def map_country_code(code): return country_code_dict.get(code, "unknown") # 用map_elements实现映射 result_df = df.with_columns( pl.col("country_code") .map_elements(map_country_code, return_dtype=pl.Utf8) .alias("remapped") ) print(result_df)
注意:优先用replace,它是向量化操作,处理大数据集时性能比map_elements高很多。
内容的提问来源于stack exchange,提问作者user17033672
相关产品推荐
相关产品推荐

