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

如何将Python DataFrame转换为指定字典格式用于to_csv的dtype参数

从指定DataFrame生成dtype字典的方法

假设你手中的示例DataFrame名为type_df,可按以下操作生成所需字典:

  • 构造示例DataFrame(若已存在可跳过)
import pandas as pd

data = {
    'Column_Name': ['FirstName', 'LastName', 'Department', 'EmployeeID'],
    'Datatype': ['string', 'string', 'integer', 'string']
}
type_df = pd.DataFrame(data)
  • 生成目标字典
    通过set_index将列名设为索引,再用to_dict转换为键值对格式:
dtype_dict = type_df.set_index('Column_Name')['Datatype'].to_dict()
  • 传入to_csv方法
    将生成的dtype_dict直接代入参数:
concat_df.to_csv(csv_buffer, sep=",", index=False, dtype=dtype_dict)

生成的字典格式完全符合需求,可直接用于to_csv的dtype参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:31:12