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

FastAPI返回结果时出现'unhashable type: list'错误的解决求助

问题:FastAPI返回Pandas DataFrame列唯一值统计时触发"TypeError: unhashable type: 'list'"错误

问题背景

编写Python代码统计Pandas DataFrame指定列的唯一值及出现频率,但通过FastAPI返回结果时,遇到TypeError: unhashable type: 'list'错误。尝试将字典转为元组后,错误仍出现在result[operation] = [(tuple(unique_value_freq_input), result12)]行。

主代码

import logging
import os
import pandas as pd

def uniq_fun(df, col_name):
    try:
        logging.info(f"Calculating the unique values and frequency for column '{col_name}'...")
        uniq_freq = df[col_name].value_counts(ascending=False)
        logging.info(f"Returning unique values and frequency for column '{col_name}' in a dictionary.")
        return uniq_freq.to_dict()
    
    except KeyError as e:
        logging.error(f"Column '{col_name}' not found in the dataframe: {e}")
        
    except Exception as e:
        logging.error(f"An unexpected error occurred while calculating the unique values and frequency for column '{col_name}': {e}")

def cleaning_and_analysis(filepath, operation=None, raw_data=None):
    file_extension = os.path.splitext(filepath)[1]
    
    if file_extension == '.csv':
        csv_dataframe = pd.read_csv(filepath, encoding='utf-8')
    
    result = {}
    if raw_data is not None and isinstance(raw_data, list):
        for i in raw_data:
             if operation=='uniqueValueFreq':   
                unique_value_freq_input= i
                result12= uniq_fun(csv_dataframe, unique_value_freq_input)
                # 报错行
                if not result:
                     result[operation] = [(tuple(unique_value_freq_input), result12)]
                else:
                     result[operation].append((tuple(unique_value_freq_input), result12))
    # 原代码缺少return语句,导致API无法获取结果

API代码

from typing import Union, Optional, Any
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from Data_Cleaning import cleaning_and_analysis

app = FastAPI()

class Item(BaseModel):
    filepath: str
    operation: Optional[str] = None
    operand: Optional[Union[list, dict, str, tuple]] = None

@app.post("/data_cleaning_route")
async def data_cleaning(item: Item):
    filepath = item.filepath
    operation_name = item.operation
    operands = item.operand
    cleaned_data = {} 
    if operands is not None and len(operands) >= 1:
        for operand in operands:
            if isinstance(operand, dict): 
                for operation_name, operand_values in operand.items():
                    cleaned_data.update(cleaning_and_analysis(filepath, operation=operation_name, raw_data=operand_values))
        return cleaned_data
    else:
        data_clean_var2 = cleaning_and_analysis(filepath=item.filepath, operation=item.operation)
        return data_clean_var2       

if __name__ == "__main__": 
     uvicorn.run(app, host="0.0.0.0", port=8000)

Postman请求负载

{
  "filepath": "C:/Downloads/shootings.csv",
  "operand": [ {"uniqueValueFreq": [["flee"], ["race"]]} ]
}

错误信息

TypeError: unhashable type: 'list'

调试信息

  • API调试输出:
C:/shootings.csv
uniqueValueFreq
[['flee'], ['race']]

API可正常读取Postman输入。

  • 主代码调试输出(print(result12)):
[(('flee',), {('Not fleeing',): 3073, ('Car',): 820, ('Foot',): 642, ('Other',): 360}), (('race',), {('White',): 2476, ('Black',): 1298, ('Hispanic',): 902, ('Asian',): 93, ('Native',): 78, ('Other',): 48})]

此为预期输出,但无法通过API返回。

解决方法

问题根源

  1. 参数传递错误:Postman传入的operand_values是[["flee"], ["race"]],循环中i为["flee"]这类列表,传入uniq_fun时,df[col_name]接收的是列表而非字符串列名,引发后续哈希错误。
  2. 函数缺少返回语句:cleaning_and_analysis未返回result,导致API无法获取处理结果。
  3. 序列化格式问题:返回结果使用元组作为元素,JSON不支持元组作为键/嵌套元素,导致FastAPI序列化失败。

修复步骤

  1. 修正列名参数传递:从列表中取出字符串类型的列名,传入uniq_fun:
  2. 添加函数返回语句:在cleaning_and_analysis末尾添加return result;
  3. 优化返回格式:改用嵌套字典结构,适配JSON序列化规则。

修复后的主代码关键部分

def cleaning_and_analysis(filepath, operation=None, raw_data=None):
    file_extension = os.path.splitext(filepath)[1]
    
    if file_extension == '.csv':
        csv_dataframe = pd.read_csv(filepath, encoding='utf-8')
    
    result = {}
    if raw_data is not None and isinstance(raw_data, list):
        for i in raw_data:
             if operation=='uniqueValueFreq':   
                # 从列表中取出字符串列名
                col_name = i[0]
                result12= uniq_fun(csv_dataframe, col_name)
                # 构建嵌套字典,适配JSON序列化
                if operation not in result:
                    result[operation] = {}
                result[operation][col_name] = result12
    return result  # 添加返回语句

修复后API返回示例

{
  "uniqueValueFreq": {
    "flee": {
      "Not fleeing": 3073,
      "Car": 820,
      "Foot": 642,
      "Other": 360
    },
    "race": {
      "White": 2476,
      "Black": 1298,
      "Hispanic": 902,
      "Asian": 93,
      "Native": 78,
      "Other": 48
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:45:14