gpt4 book ai didi

python - Pandas 数据框问题

转载 作者:行者123 更新时间:2023-11-28 17:35:10 24 4
gpt4 key购买 nike

我有这本字典:

d = {1 : [ '2' , 'Pepsi' ], 3 : [ '1' , 'Pepper' ]}

df = pd.DataFrame([[slide, i[0], i[1]] for slide, item in d.items() for i in
item], columns=['Slide', 'Level', 'Level Title'])

我想要以下输出:

slide   level    'level1 title'   'level2 title'
1 2 Pepsi
3 1 Pepper

到目前为止,我的代码输出如下:

slide   level    'level title'
1 2 Pepsi
3 1 Pepper

基本上当列表中的第一项为1时,列表中的第二项应转到'level1 title',当项目为2时,第二项应转到'level2 title'

最佳答案

如果只有两层,那么你可以使用 list comprehension ,就像这样 -

In [12]: df = pd.DataFrame([[slide, item[0], item[1], ''] if item[0] == '1' else [slide, item[0], '', item[1]] 
for slide, item in d.items()], columns=['Slide', 'Level', 'Level1 Title', 'Level2 Title'])

In [13]: df
Out[13]:
Slide Level Level1 Title Level2 Title
0 1 2 Pepsi
1 3 1 Pepper

关于python - Pandas 数据框问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253156/

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