gpt4 book ai didi

python - 将带有值列表的字典转换为数据框

转载 作者:行者123 更新时间:2023-12-03 22:02:59 25 4
gpt4 key购买 nike

说我有三本字典

dictionary_col2
{'MOB': [1, 2], 'ASP': [1, 2], 'YIP': [1, 2]}
 dictionary_col3

{'MOB': ['MOB_L001_R1_001.gz',
'MOB_L002_R1_001.gz'],
'ASP': ['ASP_L001_R1_001.gz',
'ASP_L002_R1_001.gz'],
'YIP': ['YIP_L001_R1_001.gz',
'YIP_L002_R1_001.gz']}

dictionary_col4

{'MOB': ['MOB_L001_R2_001.gz',
'MOB_L002_R2_001.gz'],
'ASP': ['ASP_L001_R2_001.gz',
'ASP_L002_R2_001.gz'],
'YIP': ['YIP_L001_R2_001.gz',
'YIP_L002_R2_001.gz']}


我想将上述字典转换为数据框。我尝试了以下方法,
df = pd.DataFrame([dictionary_col2, dictionary_col3, dictionary_col4]) df数据框看起来像,
                ASP MOB YIP
0 [1, 2] [1, 2] [1, 2]
1 [ASP_L001_R1_001.gz, ASP_L002_R1_001.gz] [MOB_L001_R1_001.gz, MOB_L002_R1_001.gz] [YIP_L001_R1_001.gz, YIP_L002_R1_001.gz]
2 [ASP_L001_R2_001.gz, ASP_L002_R2_001.gz] [MOB_L001_R2_001.gz, MOB_L002_R2_001.gz] [YIP_L001_R2_001.gz, YIP_L002_R2_001.gz]

我的目标是拥有一个包含以下列的数据框:
    col1  col2 col3              col4 
MOB 1 MOB_L001_R1_001.gz MOB_L001_R2_001.gz
MOB 2 MOB_L002_R1_001.gz MOB_L002_R2_001.gz
ASP 1 ASP_L001_R1_001.gz ASP_L001_R2_001.gz
ASP 2 ASP_L002_R1_001.gz MOB_L002_R2_001.gz
YIP 1 YIP_L001_R1_001.gz YIP_L001_R2_001.gz
YIP 2 YIP_L002_R1_001.gz YIP_L002_R2_001.gz

任何帮助/建议表示赞赏!

最佳答案

pd.DataFrame({'col2': pd.DataFrame(col2).unstack(),
'col3': pd.DataFrame(col3).unstack(),
'col4': pd.DataFrame(col4).unstack()}).reset_index(level=0)

返回
  level_0  col2                col3                col4
0 ASP 1 ASP_L001_R1_001.gz ASP_L001_R2_001.gz
1 ASP 2 ASP_L002_R1_001.gz ASP_L002_R2_001.gz
0 MOB 1 MOB_L001_R1_001.gz MOB_L001_R2_001.gz
1 MOB 2 MOB_L002_R1_001.gz MOB_L002_R2_001.gz
0 YIP 1 YIP_L001_R1_001.gz YIP_L001_R2_001.gz
1 YIP 2 YIP_L002_R1_001.gz YIP_L002_R2_001.gz

关于python - 将带有值列表的字典转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com