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

FastAPI中TypeError: unhashable type: 'list'错误修复咨询

问题修复方案

错误原因分析

  1. 字典键的无效转换:你将字符串类型的operation转为tuple,这会把字符串拆成单个字符组成的元组(比如'fillWithDesiredValue'会变成('f','i','l',...)),虽然元组可哈希,但完全不符合用操作名称作为键的逻辑。字符串本身就是可哈希类型,直接使用即可。
  2. fillna的错误用法:fillna(value=col_value, inplace=True)会直接修改原DataFrame并返回None,你后续执行df[col_name] = None,直接破坏了目标列的数据,导致后续转字典时出现异常。
  3. 重复读取CSV的冗余逻辑:每次调用cleaning_and_analysis都会重新读取原始CSV,若有多个清洗操作,后续操作无法基于前一次的清洗结果执行(当前接口单次请求仅处理一个操作,暂时不影响,但需注意优化空间)。

修复后的代码

1. 修复填充缺失值函数

def fill_num_random_fun(df, col_inputs):
    col_name = col_inputs[0]
    col_value = col_inputs[1]
    
    # 正确使用fillna:inplace=True直接修改原df,无需额外赋值
    df[col_name].fillna(value=col_value, inplace=True)
    
    result_dict = df.to_dict(orient='records')
    for record in result_dict:
        for key, value in record.items():
            if isinstance(value, float):
                record[key] = str(value)
    return result_dict

2. 修复主函数

def cleaning_and_analysis(csv_filepath, operation=None, raw_data=None):
    csv_dataframe = pd.read_csv(csv_filepath) 
    result = {}
    if raw_data is not None and isinstance(raw_data, list):
        if operation == 'fillWithDesiredValue':
            fill_with_desired_input = raw_data
            result10 = fill_num_random_fun(csv_dataframe, fill_with_desired_input)
            # 直接用operation字符串作为字典键,无需转tuple
            if operation not in result:
                result[operation] = [{tuple(raw_data): result10}]
            else:
                result[operation].append({tuple(raw_data): result10})
    return result

3. FastAPI接口优化(可选)

如果需要支持多操作链式执行(基于前一次清洗结果),可以调整逻辑避免重复读取CSV:

@app.post("/replacement_route")
async def data_cleaning(item: Item):
    filepath = item.filepath
    operands = item.operand
    cleaned_data = {}
    
    # 仅读取一次CSV,后续操作基于该DataFrame
    df = pd.read_csv(filepath)
    
    if len(operands) >= 1:
        for operand in operands:
            for operation_name, operand_values in operand.items():
                # 传入已读取的df,避免重复IO
                result = cleaning_and_analysis_with_df(df, operation=operation_name, raw_data=operand_values)
                cleaned_data.update(result)
    return cleaned_data

# 新增基于已有df的处理函数
def cleaning_and_analysis_with_df(df, operation=None, raw_data=None):
    result = {}
    if raw_data is not None and isinstance(raw_data, list):
        if operation == 'fillWithDesiredValue':
            fill_with_desired_input = raw_data
            result10 = fill_num_random_fun(df, fill_with_desired_input)
            if operation not in result:
                result[operation] = [{tuple(raw_data): result10}]
            else:
                result[operation].append({tuple(raw_data): result10})
    return result

验证修复

用你提供的Postman请求体测试,现在应该能正常返回清洗后的数据,不再抛出TypeError: unhashable type: 'list'错误。

内容的提问来源于stack exchange,提问作者Apoorva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:44