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

如何创建Python装饰器,将返回Pandas DataFrame的函数结果转换为指定格式字典

Convert DataFrame-returning Functions to Dict with a Decorator

Here's how you can implement the df_to_dict decorator to achieve exactly what you want. This decorator will wrap any function that returns a pandas DataFrame, intercept its output, convert it to your desired dictionary format, and return that dict instead:

import pandas as pd

def df_to_dict(func):
    def wrapper(*args, **kwargs):
        # Execute the original function to get the DataFrame
        df_result = func(*args, **kwargs)
        # Convert DataFrame to the target dictionary structure
        return {col: df_result[col].to_list() for col in df_result.columns}
    return wrapper

Usage Example

Now you can apply it to your function using the decorator syntax as requested:

@df_to_dict
def some_func_that_returns_df():
    df = pd.DataFrame([1,2,3,4,5], columns=['a'])
    return df

# Call the function - it returns the dict directly
df_as_dict = some_func_that_returns_df()
print(df_as_dict)  # Output: {'a': [1, 2, 3, 4, 5]}

Handling Functions with Arguments

This decorator is flexible enough to work with functions that accept parameters too. For example:

@df_to_dict
def create_custom_df(data_points, col_name):
    return pd.DataFrame(data_points, columns=[col_name])

result = create_custom_df([10, 20, 30, 40], 'numbers')
print(result)  # Output: {'numbers': [10, 20, 30, 40]}

How It Works

  • The df_to_dict decorator takes the target function as input.
  • The inner wrapper function captures any arguments (*args, **kwargs) passed to the original function, so it works for any function signature.
  • It calls the original function to get the DataFrame result.
  • It converts the DataFrame to your specified dictionary format by iterating over each column and converting the column values to a list.
  • Finally, it returns the transformed dictionary instead of the original DataFrame.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:44:08