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

如何在Python中将数据集的产品列表拆分为多列?

解决方法:将字符串形式的列表拆分为多列

你的问题核心在于Products列的内容是字符串格式的列表,并非真正的Python列表对象,直接用str.split()会按字符拆分,自然得不到预期结果。需要先把字符串转换成真实列表,再展开为多列,具体步骤如下:

  1. 导入所需库
import pandas as pd
import ast
  1. 加载你的数据集(这里用示例数据演示)
data = {
    'Store': ['001', '002'],
    'Products': ["['Skettles','M&M Candies', 'Dove Chocolates']", 
                 "['Danimals yogurt', 'Noosa', 'Graham Crackers','Dove Chocolates']"]
}
df = pd.DataFrame(data)
  1. 将字符串转为真实列表
    用ast.literal_eval()解析字符串格式的列表,把它转换成可操作的Python列表:
df['Products'] = df['Products'].apply(ast.literal_eval)
  1. 展开列表为多列并命名
    把列表列拆分成独立列,同时给列名加上Product前缀:
product_cols = df['Products'].apply(pd.Series)
product_cols.columns = [f'Product{i+1}' for i in product_cols.columns]
  1. 合并原Store列与新生成的产品列
result_df = pd.concat([df['Store'], product_cols], axis=1)

最终得到的result_df就是你想要的格式:

Store         Product1      Product2          Product3         Product4
0   001        Skettles  M&M Candies  Dove Chocolates              NaN
1   002  Danimals yogurt        Noosa  Graham Crackers  Dove Chocolates

(如果需要把空值替换为空白字符串,可以添加result_df = result_df.fillna(''))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:15:21