【问题标题】:Get values from list with dictionary使用字典从列表中获取值
【发布时间】:2022-08-16 21:27:16
【问题描述】:

我有一个字典列表,我需要从中获取值并创建数据框。我的列表如下所示:

> list_values = [{\'id\': 42,
>               \'start_time\': 1660186432206,
>              \'update_time\': 1660186432235,
>               \'participants\': [{\'object_type\': \'device\',
>                                \'object_id\': 429496764},
>                                {\'object_type\': \'device_2\',
>                                \'object_id\': 429494234},
>                                {\'object_type\': \'device_3\',
>                                \'object_id\': 429494123}],
>               \'title\':\'Something\'},
>               {\'id\': 422,
>               \'start_time\': 1623186432206,
>              \'update_time\': 1690186432235,
>               \'participants\': [{\'object_type\': \'devicedf\',
>                                \'object_id\': 429496764},
>                                {\'object_type\': \'device_as\',
>                                \'object_id\': 429494234},
>                                {\'object_type\': \'device_ad\',
>                                \'object_id\': 4294657123}],
>               \'title\':\'Something213\'}]

当然,这个列表更大。所以基本上我需要创建一个如下所示的 DF:

id    start_time       object_id
42    1660186432206    429496764
42    1660186432206    429494234
42    1660186432206    429494123
422   1623186432206    429496764
422   1623186432206    429494234 
422   1623186432206    4294657123

我可以通过以下方式获取 ID 和开始时间:

id = [a[\'start_time\'] for a in list_values ]
start_time = [b[\'start_time\'] for b in list_values ]

不幸的是,我无法获得有关 object_id 的信息,并将其与 id 和 start_time 结合起来以创建 DF。你知道我该怎么做吗?

  • 您的输入结构是嵌套的。使用 [part[\'object_id\'] for part in a[\'participant\']] 访问 object_id 有什么问题?

标签: python list dataframe dictionary for-loop


【解决方案1】:

尝试:

df = pd.DataFrame(list_values).explode("participants")
df["object_type"] = df.participants.str["object_id"]
print(df[["id", "start_time", "object_type"]])

印刷:

    id     start_time  object_type
0   42  1660186432206    429496764
0   42  1660186432206    429494234
0   42  1660186432206    429494123
1  422  1623186432206    429496764
1  422  1623186432206    429494234
1  422  1623186432206   4294657123

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多