gpt4 book ai didi

python - 以ID为键的 Pandas 数据框到字典

转载 作者:行者123 更新时间:2023-11-28 22:23:18 25 4
gpt4 key购买 nike

下面是我的 pandas 数据框,现在我想从中创建字典,以便记录字典,其中键是 record_ids,值是字典,键是字段名称,像这样:

我使用了 df.to_dict() 函数,但不确定如何使用它使 record_ids 作为键。

{123342: {'Address': 'Brunswick',
'Id': '123342',
'Name': 'Rachels Hunt',
'Unname': 'VB INDUSTRIES',
'no': '6032',
'zip': '01123'}}

Dataframe

最佳答案

让我们使用 set_indexto_dict():

df.set_index(df.Id).T.to_dict()

输出:

{123342: {'Address': 'Brunswick',
'Id': 123342,
'Name': 'Rachels Hunt',
'Unname': 'VB INDUSTRIES',
'no': 6032,
'zip': 1123}}

注意:我没有将 Id 列移动到索引中,而是创建了一个与 Id 列相同的新索引。

在哪里

print(df)

Id Address Name Unname no zip
0 123342 Brunswick Rachels Hunt VB INDUSTRIES 6032 1123

编辑下面的评论:

df.apply(lambda x: x.astype(str)).set_index(df.Id).T.to_dict()

输出:

{123342: {'Address': 'Brunswick',
'Id': '123342',
'Name': 'Rachels Hunt',
'Unname': 'VB INDUSTRIES',
'no': '6032',
'zip': '1123'}}

关于python - 以ID为键的 Pandas 数据框到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081076/

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