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

如何将pandas DataFrame中逗号分隔字符串拆分后导出为指定格式JSON

解决方法

你遇到的问题是因为没有对逗号分隔的字符串做拆分,直接把完整字符串塞进了列表,按下面的方法修改即可:

方法1:修改你现有的循环逻辑

只需要调整情感列的赋值逻辑,用, 作为分隔符拆分字符串即可,额外增加空值判断避免缺失值报错:

import json
import pandas as pd

b = []
for i in range(len(df)):
    x = {}
    x['Group Name'] = df.iloc[i]['group_name']
    # 拆分正向情感字符串
    pos_sentiment = df.iloc[i]['Positive_Sentiment']
    x['Positive Sentiment'] = pos_sentiment.split(', ') if pd.notna(pos_sentiment) else []
    # 拆分负向情感字符串
    neg_sentiment = df.iloc[i]['Negative_Sentiment']
    x['Negative Sentiment'] = neg_sentiment.split(', ') if pd.notna(neg_sentiment) else []
    b.append(x)

# 导出JSON
with open('AnalysisResults.json', 'w') as f:
    json.dump(b, f, indent = 2)

方法2:更简洁的Pandas向量化写法(无需手动写循环)

直接用Pandas内置方法完成列重命名、字符串拆分、导出全流程,执行效率更高:

import pandas as pd

# 1. 重命名列匹配输出要求的键名
result_df = df.rename(columns={
    'group_name': 'Group Name',
    'Positive_Sentiment': 'Positive Sentiment',
    'Negative_Sentiment': 'Negative Sentiment'
})

# 2. 对情感列执行逗号分隔拆分
result_df['Positive Sentiment'] = result_df['Positive Sentiment'].str.split(', ')
result_df['Negative Sentiment'] = result_df['Negative Sentiment'].str.split(', ')

# 3. 直接导出为符合要求的JSON,force_ascii=False可保留中文等非ASCII字符
result_df.to_json('AnalysisResults.json', orient='records', indent=2, force_ascii=False)

注意:如果需要匹配你示例中Postive Sentiment的拼写(为笔误少了字母i),自行修改对应的键名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:15:03