将Pandas DataFrame转换为嵌套字典,其中键值对是列

3hvapo4f  于 2023-04-04  发布在  其他
关注(0)|答案(4)|浏览(113)

我有一个三列的pandas dataframe。假设它看起来像这样:

test_df = pd.DataFrame({
    'key1': [1, 1, 1, 1, 2, 2, 2],
    'key2': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    'value': ['a-mapped', 'b-mapped', 'c-mapped', 'd-mapped', 'e-mapped', 'f-mapped', 'g-mapped']
})
> test_df

    key1    key2    value
0   1       a   a-mapped
1   1       b   b-mapped
2   1       c   c-mapped
3   1       d   d-mapped
4   2       e   e-mapped
5   2       f   f-mapped
6   2       g   g-mapped

我想返回一个嵌套字典,其中第一个键是key1,然后第二个键值对是{key2: value}

{
    1: {'a': 'a-mapped', 'b': 'b-mapped', 'c': 'c-mapped', 'd': 'd-mapped'},
    2: {'e': 'e-mapped', 'f': 'f-mapped', 'g': 'g-mapped'}
}

我可以通过使用一些循环来实现这一点:

desired_result = {}
for key1 in test_df.key1:
    desired_result[key1] = {}
    
for idx, row in test_df.iterrows():
    desired_result[row.key1][row.key2] = row.value

有没有更有效的方法?

whhtz7ly

whhtz7ly1#

试试看:

out = test_df.groupby("key1").apply(lambda x: dict(zip(x["key2"], x["value"]))).to_dict()
print(out)

图纸:

{
    1: {"a": "a-mapped", "b": "b-mapped", "c": "c-mapped", "d": "d-mapped"},
    2: {"e": "e-mapped", "f": "f-mapped", "g": "g-mapped"},
}
kq0g1dla

kq0g1dla2#

类似于@Andrej,但使用字典理解:

out = {k: dict(zip(g['key2'], g['value'])) for k, g in test_df.groupby('key1')}

输出:

{1: {'a': 'a-mapped', 'b': 'b-mapped', 'c': 'c-mapped', 'd': 'd-mapped'},
 2: {'e': 'e-mapped', 'f': 'f-mapped', 'g': 'g-mapped'}}
guz6ccqo

guz6ccqo3#

让我们试试

out_d = test_df.set_index('key2').groupby('key1')['value'].agg(dict).to_dict()
Out[14]: 
{1: {'a': 'a-mapped', 'b': 'b-mapped', 'c': 'c-mapped', 'd': 'd-mapped'},
 2: {'e': 'e-mapped', 'f': 'f-mapped', 'g': 'g-mapped'}}
avwztpqn

avwztpqn4#

def function1(dd:pd.DataFrame):
    return dd.set_index("key2")['value'].to_dict()

test_df.groupby('key1').apply(function1).to_dict()

输出:

{1: {'a': 'a-mapped', 'b': 'b-mapped', 'c': 'c-mapped', 'd': 'd-mapped'},
 2: {'e': 'e-mapped', 'f': 'f-mapped', 'g': 'g-mapped'}}

相关问题