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

使用Pandas存值为列表的defaultdict为CSV遇长度错误,如何将列表存入单个单元格?

How to Save a defaultdict with Uneven List Lengths to CSV (Putting Long Lists in Single Cells)

Hey there! That ValueError pops up because Pandas expects every column in a DataFrame to have the same number of elements. Your id list only has 1 entry, but success has 3—so Pandas can't line them up into rows automatically.

To stuff the entire success list into a single CSV cell, we just need to adjust the data so each column has matching lengths. Here are a couple of straightforward ways to do it:

Method 1: Wrap the long list in a nested list

Modify your defaultdict directly to turn the success list into a single element (which is the original list itself):

import pandas as pd
import collections

dd = collections.defaultdict(list)
dd['id'].append('42')
for x in range(3):
    dd['success'].append(1)

# Key fix: Turn the success list into a single-element nested list
dd['success'] = [dd['success']]

print(dd)
# Output: defaultdict(<class 'list'>, {'id': ['42'], 'success': [[1, 1, 1]]})

# Now export to CSV (index=False removes the extra row numbers)
pd.DataFrame(dd).to_csv('test.csv', index=False)

When you open the CSV, the success cell will contain [1, 1, 1].

Method 2: Build the DataFrame manually

If you don't want to modify the original defaultdict, construct the DataFrame with explicit row alignment:

import pandas as pd
import collections

dd = collections.defaultdict(list)
dd['id'].append('42')
for x in range(3):
    dd['success'].append(1)

# Create a DataFrame with one row: id uses its list, success uses the full list as one entry
df = pd.DataFrame({
    'id': dd['id'],
    'success': [dd['success']]
})

df.to_csv('test.csv', index=False)

Bonus: Format the list as a plain comma-separated string

If you don't want the square brackets in your CSV, convert the list to a string first:

dd['success'] = [','.join(map(str, dd['success']))]
# Now the success cell will have "1,1,1" instead of "[1, 1, 1]"

All these approaches ensure each column has the same length, so Pandas can export the data without throwing that length mismatch error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:36:35