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

使用defaultdict按列值配对DataFrame字段时无法将datetime转回日期格式

解决方法

你的Date列当前为datetime.date类型,直接转换为字符串就会自动输出YYYY-MM-DD格式,可选择以下任意一种方案修改:

方案一:生成字典时直接转换(无需修改前置逻辑)

仅修改字典生成阶段的append行即可,修改后代码如下:

from collections import defaultdict

res = defaultdict(list)
for index, row in tqdm(df_grouped.iterrows(), position=0, leave=True):
    # 仅新增str()包裹Date字段
    res[row["Device"]].append((str(row["Date"]), round(row["Level"],2)))

方案二:提前转换Date列格式

在分组完成后、生成字典前新增一行代码,将Date列整体转换为字符串格式,后续字典生成代码无需调整:

df_grouped = df.groupby([df['Device'], df['Date']])['Level'].mean().reset_index()
# 新增以下行
df_grouped['Date'] = df_grouped['Date'].astype(str)

from collections import defaultdict

res = defaultdict(list)
for index, row in tqdm(df_grouped.iterrows(), position=0, leave=True):
    res[row["Device"]].append((row["Date"], round(row["Level"],2)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 03:39:04