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

如何将单元格转换为DataFrame?并将指定字典转为单行带表头DataFrame

如何将字典转换为单行DataFrame及处理DataFrame单元格中的字典

一、直接将给定字典转为单行DataFrame

直接借助pandas的DataFrame构造方法,把字典包裹在列表里传入,就能生成以字典键为表头的单行DataFrame:

import pandas as pd

# 定义目标字典
profile_dict = {
    'symbol': 'AAPL', 
    'price': 150.72, 
    'beta': 1.246644, 
    'volAvg': 89576498, 
    'mktCap': 2397668846469, 
    'lastDiv': 0.91, 
    'range': '129.04-182.94', 
    'changes': 1.93, 
    'companyName': 'Apple Inc.', 
    'currency': 'USD', 
    'cik': '0000320193', 
    'isin': 'US0378331005', 
    'cusip': '037833100',
    'isFund': False
}

# 转换为单行DataFrame
single_row_df = pd.DataFrame([profile_dict])
print(single_row_df)

运行后会得到一行数据,表头就是字典里的symbol、price等字段。

二、处理现有DataFrame单元格中的字典

如果该字典已经存在于某个DataFrame的profile列单元格中,可按以下方式处理:

1. 提取单元格字典生成新的单行DataFrame

假设df是包含profile列的DataFrame,取对应单元格的字典后转换:

# 提取第一行profile单元格的字典内容(根据实际行索引调整)
cell_dict = df['profile'].iloc[0]

# 转换为单行DataFrame
result_df = pd.DataFrame([cell_dict])

2. 将字典字段展开到原DataFrame中

如果想把字典的键值对直接作为新列合并到原DataFrame,用pd.json_normalize()更高效:

# 展开profile列的字典为独立列
expanded_cols = pd.json_normalize(df['profile'])

# 合并到原DataFrame(移除原profile列)
final_df = pd.concat([df.drop('profile', axis=1), expanded_cols], axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:15:35