如何将含复杂Series的DataFrame转换为目标结构的新DataFrame
解决方案
假设你的原始DataFrame名为original_df,其中存储复杂结构的列名为CashFlow,可以通过以下步骤实现转换:
提取字典中的列表数据
先把每个单元格里字典的CashFlowDto对应列表提取出来:original_df['cash_flow_items'] = original_df['CashFlow'].apply(lambda x: x['CashFlowDto'])将列表拆分为多行
使用explode方法把每个列表中的元素拆成单独的行:exploded_df = original_df.explode('cash_flow_items')将字典结构解析为列
用pd.json_normalize把每行的字典转换成对应的列:import pandas as pd final_df = pd.json_normalize(exploded_df['cash_flow_items'])保留原始索引(可选)
如果需要保留原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
相关产品推荐
相关产品推荐

