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

如何将字典列表赋值给Dask DataFrame列?遇类型错误求解决

在Dask中实现Pandas字典列表列赋值的方法

你在Pandas中通过iterrows()生成字典列表并赋值给DataFrame列的代码,在Dask中报错是因为Dask不支持直接将列表赋值给列——Dask基于分布式分区设计,逐行迭代的iterrows()不仅效率极低,也不符合其数据处理模式。

先修正你原代码里的两处问题:

  1. 重复定义了'day'键,会导致后值覆盖前值,建议将周几的字段重命名为'weekday'
  2. 'month'(row['closingdate'].month,存在语法错误,应改为'month': row['closingdate'].month,

以下是两种Dask的实现方案:

方案一:使用map_partitions(推荐大数量场景)

利用map_partitions将每个分区作为Pandas DataFrame处理,保留你熟悉的逐行逻辑,同时适配Dask的分布式计算:

import dask.dataframe as dd
from pandas import DataFrame

def process_partition(df: DataFrame):
    df['closingDate'] = [
        {
            'bin': 1,
            'date': row['closingdate'].date(),
            'hour': row['closingdate'].hour,
            'weekday': row['closingdate'].weekday() + 1,
            'day': row['closingdate'].day,
            'year': row['closingdate'].year,
            'month': row['closingdate'].month,
            'quarter': (row['closingdate'].month // 3) + 1,
            'week': row['closingdate'].week
        } for idx, row in df.iterrows()
    ]
    return df

# 假设你的Dask DataFrame为ddf
ddf = ddf.map_partitions(process_partition)
# 若需立即计算结果,可调用compute()
# ddf = ddf.compute()

方案二:使用apply逐行处理

适合小数据量场景,直接对每行应用生成字典的函数:

import dask.dataframe as dd

def create_closing_date_dict(row):
    return {
        'bin': 1,
        'date': row['closingdate'].date(),
        'hour': row['closingdate'].hour,
        'weekday': row['closingdate'].weekday() + 1,
        'day': row['closingdate'].day,
        'year': row['closingdate'].year,
        'month': row['closingdate'].month,
        'quarter': (row['closingdate'].month // 3) + 1,
        'week': row['closingdate'].week
    }

# 指定meta参数声明返回类型为object
ddf['closingDate'] = ddf.apply(create_closing_date_dict, axis=1, meta=object)

额外注意事项

  • 确保closingdate列是datetime类型,若不是需先转换:ddf['closingdate'] = dd.to_datetime(ddf['closingdate'])
  • 大数量场景下优先选择map_partitions,其性能远高于逐行apply

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:01:11