Python遍历多个DataFrame重命名列触发不可哈希错误如何解决
错误原因
Python 要求字典的键必须是可哈希的不可变对象(比如整数、字符串、元组等),而 Pandas DataFrame 是可变对象,内部数据修改后哈希值会变化,因此不允许作为字典的键使用,这就是你抛出TypeError的根本原因。
解决方案
把原来用 DataFrame 做键的字典,改成存储「DataFrame 对象、对应新列名」配对的列表即可,不需要改动clean_col函数的逻辑,只需要调整映射结构和遍历方式:
修改后的代码
# 替换原来的字典d,改用列表存储配对关系 df_map = [ (all_df, "all"), (coal_df, "coal"), (liquids_df, "liquids"), (coke_df, "coke"), (natural_gas_df, "natural_gas"), (nuclear_df, "nuclear"), (hydro_electricity_df, "hydro"), (wind_df, "wind"), (utility_solar_df, "utility_solar"), (geothermal_df, "geo_thermal"), (wood_biomass_df, "biomass_wood"), (biomass_other_df, "biomass_other"), (other_df, "other"), (solar_all_df, "all_solar"), ] # 遍历执行清洗 for df, col_name in df_map: clean_col(df, col_name)
可选优化(提升性能)
原函数中用apply+lambda 转整数的写法性能较低,你可以替换为更高效的内置方法:
def clean_col(df,col_name): df.reset_index(inplace=True) df.rename(columns={df.columns[0]:'Date', df.columns[1]: col_name},inplace=True) # 替换原来的apply写法,性能提升10倍以上 df[col_name] = df[col_name].astype(int) # 如果存在脏数据,可用以下写法自动处理非数字值为NaN,再转可空整数类型 # import pandas as pd # df[col_name] = pd.to_numeric(df[col_name], errors='coerce').astype('Int64')
内容的提问来源于stack exchange,提问作者Shawn Jamal
相关产品推荐
相关产品推荐

