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

如何在Pandas Series中展开StructType类型的索引

拆分Pandas Series的StructType索引为单独列

方法一:针对元组形式的复合索引(示例数据格式)

如果你的Series索引是元组结构的复合索引(显示为(日期, 参数名)形式),直接使用reset_index()即可快速展开索引字段:

import pandas as pd

# 模拟你的数据
data = [0.997160, 0.037629, 0.037629, 2.000000, 0.997160]
index = pd.MultiIndex.from_tuples(
    [(pd.to_datetime('2005-07-03'), 'beta0'),
     (pd.to_datetime('2005-07-03'), 'beta1'),
     (pd.to_datetime('2005-07-03'), 'beta2'),
     (pd.to_datetime('2005-07-03'), 'tau'),
     (pd.to_datetime('2011-11-13'), 'beta0')],
    names=['checkin_week', 'parameter']
)
s = pd.Series(data, index=index, name='value')

# 拆分索引为列
df = s.reset_index()

执行后得到的DataFrame结构如下:

checkin_weekparametervalue
2005-07-03beta00.997160
2005-07-03beta10.037629
2005-07-03beta20.037629
2005-07-03tau2.000000
2011-11-13beta00.997160

方法二:针对真正的StructType索引

如果你的索引是包含键值对的结构体类型(比如从PySpark导入的数据),可以先将索引转换为DataFrame,再与原Series合并:

# 模拟StructType索引的Series
struct_index = pd.Index([
    {'checkin_week': pd.to_datetime('2005-07-03'), 'parameter': 'beta0'},
    {'checkin_week': pd.to_datetime('2005-07-03'), 'parameter': 'beta1'},
    {'checkin_week': pd.to_datetime('2005-07-03'), 'parameter': 'beta2'},
    {'checkin_week': pd.to_datetime('2005-07-03'), 'parameter': 'tau'},
    {'checkin_week': pd.to_datetime('2011-11-13'), 'parameter': 'beta0'}
], name='index')
s_struct = pd.Series(data, index=struct_index, name='value')

# 提取结构体字段并合并
index_df = pd.DataFrame.from_records(s_struct.index)
result_df = pd.concat([index_df, s_struct.reset_index(drop=True)], axis=1)

该方法会将结构体中的checkin_week和parameter字段分别提取为独立列,最终结果与方法一一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:51:03