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

Pandas读取字典生成DataFrame时文本拆分多列的解决方法

解决步骤

先导入必要的库,再按以下流程处理:

  1. 将原嵌套字典转为DataFrame
import pandas as pd
import numpy as np

original_dict = {
    0: {0: "It's chic", 1: 'Samsung and Panasonic were overpriced.', 2: 'Others that compare are much more expensive.', 3: "Can't beat it at the price.", 4: 'I bought the more expensive case  for my 8.9 but it made my kindle very heavy.'},
    1: {0: " looks expensive but it's affordable", 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan},
    2: {0: ' what more can you want.', 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan}
}

df = pd.DataFrame(original_dict)
  1. 合并每行的非空文本
    原字典转成DataFrame后会生成3列(对应外层键0、1、2),我们需要把每行里的非空字符串拼接起来:
df['combined'] = df.apply(lambda row: ''.join(str(val) for val in row if pd.notna(val)), axis=1)
  1. 转换为目标格式的字典
    把合并后的单列数据转成你需要的嵌套字典结构:
dict_2 = {0: df['combined'].to_dict()}

运行以上代码后,dict_2就会和你指定的格式完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:25:20