gpt4 book ai didi

python - 转换词典列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:02 24 4
gpt4 key购买 nike

尝试跟踪各种应用随时间的排名:

# I need to convert this list of dicts: 

[{"Date" : "7/1/16", "Foo": 32, "Bar" : 49, 'Spam': 55},
{"Date" : "7/2/16", "Foo": 43, "Bar" : 44, 'Spam': 77},
{"Date" : "7/3/16", "Foo": 23, "Bar" : 47, 'Spam': 63}]

# Into this list of dicts:

[{"AppTitle" : "Foo", "7/1/16" : 32, "7/2/16" : 43, "7/3/16" : 23},
{"AppTitle" : "Bar", "7/1/16" : 49, "7/2/16" : 44, "7/3/16" : 47},
{"AppTitle" : "Spam", "7/1/16" : 55, "7/2/16" : 77, "7/3/16" : 63}]

本质上,我需要创建一个可以与包装器一起使用的数据框我为 python 的 CSV 模块构建。我查看了大量与从字典列表创建数据框相关的问题,但没有一个完全符合我的需要。

供引用:Foo、Bar 和 Spam 是 App 标题,数字是指定日期的排名

最佳答案

import pandas as pd
df = pd.DataFrame([{"Date" : "7/1/16", "Foo": 32, "Bar" : 49, 'Spam': 55},
{"Date" : "7/2/16", "Foo": 43, "Bar" : 44, 'Spam': 77},
{"Date" : "7/3/16", "Foo": 23, "Bar" : 47, 'Spam': 63}])

从这个 DataFrame 中,您可以使用转置方法获得结果:

df.set_index('Date').T.reset_index().rename(columns={'index': 'AppTitle'}).to_dict('r')
Out:
[{'7/1/16': 49, '7/2/16': 44, '7/3/16': 47, 'AppTitle': 'Bar'},
{'7/1/16': 32, '7/2/16': 43, '7/3/16': 23, 'AppTitle': 'Foo'},
{'7/1/16': 55, '7/2/16': 77, '7/3/16': 63, 'AppTitle': 'Spam'}]

关于python - 转换词典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38646853/

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