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

如何调整DataFrame结构避免列表,实现df1到df2的格式转换?

问题描述

我有一个DataFrame df1,希望将其转换为df2的格式,避免使用列表存储数据。以df1第一行为例:包含两组人数分别为18和17的群体,报告的事件包括Asthma和Pneumonia;第一组中有5人患Asthma、3人患Pneumonia,第二组中有6人患Asthma、2人患Pneumonia。

df1中各群体总人数、报告事件、事件对应人数均以列表形式存储,需转换为df2的扁平化列结构,缺失事件对应数值以0填充。

相关代码示例如下:

import pandas as pd
df1 = pd.DataFrame(data= {'col1': [1, 2], 'col2': [3, 4], 'total of each group':[[18,17],[15,16]],'Reported events for each group':[['Asthma','Pneumonia'],['Asthma','Pneumonia','Death']],'Number of events':[[5,6,3,2],[5,6,7,2,3,4]]})

df2=pd.DataFrame(data= {'col1': [1, 2], 'col2': [3, 4], 'total of group 1':[18,15], 'total of group 2':[17,16],'Asthma grp1':[5,5],'Asthma grp2':[6,6],'Pneumonia grp1':[3,7],'Pneumonia grp2':[2,2],'Death grp 1':[0,3],'Death grp 2':[0,4]})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:20:44