使用Pandas存值为列表的defaultdict为CSV遇长度错误,如何将列表存入单个单元格?
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

