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

如何将存储字典的Python Series对象提取字段转换为pd.DataFrame

解决方案

你可以直接通过pandas内置的Series字典访问方法提取目标字段,以下是两种可行实现:


方法1:仅提取count字段(推荐,性能最优)

直接通过str.get访问字典的count键,再转DataFrame:

# 假设你的原始Series命名为 people_series
count_df = people_series.str.get('count').to_frame(name='count')

该方法会自动保留原始Series的索引,生成仅含count列的DataFrame。


方法2:全字典转DataFrame(适合后续要提取更多字段的场景)

如果后续还需要提取distances下的嵌套字段,可以先把所有字典值转成DataFrame再筛选列:

import pandas as pd
# 转换全量字典为DataFrame,保留原始索引
full_df = pd.DataFrame(people_series.tolist(), index=people_series.index)
# 提取count列
count_df = full_df[['count']]

验证示例

你可以用以下测试代码验证逻辑正确性:

import pandas as pd
# 构造和你结构一致的测试Series
people_series = pd.Series(
    [
        {'count': 0, 'distances': {'values': [], 'unit': 'm'}},
        {'count': 3, 'distances': {'values': [1.2, 2.5], 'unit': 'm'}},
        {'count': 5, 'distances': {'values': [0.8, 3.1, 4.7], 'unit': 'm'}}
    ],
    name='people'
)

# 执行方法1
count_df = people_series.str.get('count').to_frame(name='count')
print(count_df)

输出结果:

count
0      0
1      3
2      5

内容的提问来源于stack exchange,提问作者S. Hyland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:36:03