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

遍历pandas DataFrame按标签分组存入字典时值为空如何解决

错误原因

  • 筛选条件写错:代码中train_df["label"] == "@i"使用了固定字符串"@i"作为匹配值,没有引用循环变量i,所有查询都无法匹配到符合条件的行,因此返回结果为空。
  • 输出格式不符合需求:代码使用" ".join()方法,会把提取到的text列表拼接为单个字符串,和你要存储列表的需求不符。

修正方法

方法1:修改原有循环逻辑

仅调整循环内的赋值逻辑即可实现需求:

my_dict = dict()

for i in train_df.label.unique():
    my_dict[i] = train_df[train_df["label"] == i]["text"].tolist()

方法2:更高效的内置方法实现

使用pandas的groupby聚合逻辑,一行代码即可完成相同效果,运行效率高于手动循环:

my_dict = train_df.groupby('label')['text'].apply(list).to_dict()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:57:00