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

如何将含复杂Series的DataFrame转换为目标结构的新DataFrame

解决方案

假设你的原始DataFrame名为original_df,其中存储复杂结构的列名为CashFlow,可以通过以下步骤实现转换:

  1. 提取字典中的列表数据
    先把每个单元格里字典的CashFlowDto对应列表提取出来:

    original_df['cash_flow_items'] = original_df['CashFlow'].apply(lambda x: x['CashFlowDto'])
    
  2. 将列表拆分为多行
    使用explode方法把每个列表中的元素拆成单独的行:

    exploded_df = original_df.explode('cash_flow_items')
    
  3. 将字典结构解析为列
    用pd.json_normalize把每行的字典转换成对应的列:

    import pandas as pd
    final_df = pd.json_normalize(exploded_df['cash_flow_items'])
    
  4. 保留原始索引(可选)
    如果需要保留原DataFrame的整数索引列,将其合并到结果中:

    final_df = final_df.join(exploded_df.reset_index()[['index']])
    # 调整列顺序,把原始索引放到最前面
    final_df = final_df[['index', 'TicketId', 'Type', 'Amount', 'PercentualAmount', 'MaturityDate', 'PaymentDate']]
    

执行完以上步骤后,就能得到你需要的目标DataFrame——每行对应原列表中的一个字典项,所有键都转换为单独的列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:07:23