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

将DataFrame中字典列表值合并为单列表时遇ValueError问题求助

解决Pandas赋值列表时的ValueError问题

Hey there! Let's sort out this ValueError you're hitting when trying to create the rr_list column. The issue comes down to how pandas handles assigning lists to cells with loc—let's break down the fix.

最优解决方案:用apply批量处理

Instead of looping through each index (which is also less efficient), use pandas' built-in apply function to process every row in one go. This avoids the length-mismatch error entirely:

df_sim['rr_list'] = df_sim['rrintervals'].apply(lambda x: [val for sub_dict in x for val in sub_dict['values']])

This works because apply takes each entry in the rrintervals column, runs the list comprehension to flatten all the values lists, and stores the resulting flat list directly as the value in the new rr_list column.

为什么你的循环报错?

When you use df_sim.loc[i, "rr_list"] = [your_flat_list], pandas interprets the list as a sequence it needs to assign across multiple columns (not as a single value for one cell). Since your list has more elements than the number of columns you're targeting (just one), it throws that "equal len keys and value" error.

如果坚持用循环:改用at

If you prefer a loop-based approach, swap loc for at—at is designed for single-cell assignments and won't trigger the length check:

for i in df_sim.index:
    df_sim.at[i, "rr_list"] = [val for sub_dict in df_sim.loc[i, "rrintervals"] for val in sub_dict['values']]

验证结果

For your sample input:

[{'values': [727.0]}, {'values': [693.0, 688.0]}, {'values': [689.0]}, {'values': [699.0]}]

Both methods will produce the expected output in rr_list:

[727.0, 693.0, 688.0, 689.0, 699.0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:59:04