Pandas:Groupby并使用剩余的列名称和值创建dict

2024-05-14 08:25:33 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的df

In [425]: df
Out[425]: 
     a  b  c      d
0  abc  1  1   True
1  abd  1  1  False
2  abe  1  2  False
3  abf  1  2   True
4  abg  2  2   True

我想对bc列进行分组,并用剩余的列名及其值创建dict

预期输出:

[
    {
        "b": 1,
        "c": 1,
        "attr":[
            {
            "a": "abc",
            "d": True
            },
            {
            "a": "abd",
            "d": False
            }
        ]
    },
    {
        "b": 1,
        "c": 2,
        "attr":[
            {
            "a": "abe",
            "d": False
            },
            {
            "a": "abf",
            "d": True
            }
        ]
    },
    {
        "b": 2,
        "c": 2,
        "attr":[
            {
            "a": "abg",
            "d": True
            }
        ]
    }
]

我的尝试:

In [423]: df.set_index(['b', 'c']).agg(list, 1).to_dict()
Out[423]: {(1, 1): ['abd', False], (1, 2): ['abf', True], (2, 2): ['abg', True]}

我能够分组并创建dict,但不知道如何将列名与之一起放置


Tags: infalsetruedfindexoutdictagg
2条回答

将自定义lambda函数与^{}中的^{}一起使用:

d = (df.groupby(['b','c'])[['a','d']]
       .apply(lambda x: x.to_dict('records'))
       .reset_index(name='attr')
       .to_dict('records'))
print (d)
[{'b': 1, 'c': 1, 'attr': [{'a': 'abc', 'd': True}, 
                           {'a': 'abd', 'd': False}]},
  {'b': 1, 'c': 2, 'attr': [{'a': 'abe', 'd': False},
                            {'a': 'abf', 'd': True}]}, 
  {'b': 2, 'c': 2, 'attr': [{'a': 'abg', 'd': True}]}]

如果有多个列,则可选择:

d = (df.set_index(['b','c'])
       .groupby(['b','c'])
       .apply(lambda x: x.to_dict('records'))
       .reset_index(name='attr')
       .to_dict('records'))
print (d)

在具有多个组的大型数据帧中的性能:

np.random.seed(123)
N = 1000000

L1 = list('abcdefghijklmno')
L = np.random.randint(100,size=N)
df = pd.DataFrame({'a': np.random.choice(L1, N),
                   'b': np.random.choice(L, N),
                   'c':np.random.choice(L, N),
                   'd':np.random.choice([True, False], N),})
print (df)

In [51]: %timeit [dict(b=b, c=c, attr=d.to_dict('records')) for (b, c), d in df.set_index(['b', 'c']).groupby(['b', 'c'])]
6.01 s ± 247 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [53]: %timeit (df.groupby(['b','c'])[['a','d']].apply(lambda x: x.to_dict('records')).reset_index(name='attr').to_dict('records'))
4.79 s ± 137 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

理解力

[dict(b=b, c=c, attr=d.to_dict('records'))
 for (b, c), d in df.set_index(['b', 'c']).groupby(['b', 'c'])]

[{'b': 1, 'c': 1, 'attr': [{'a': 'abc', 'd': True}, {'a': 'abd', 'd': False}]},
 {'b': 1, 'c': 2, 'attr': [{'a': 'abe', 'd': False}, {'a': 'abf', 'd': True}]},
 {'b': 2, 'c': 2, 'attr': [{'a': 'abg', 'd': True}]}]
​

相关问题 更多 >

    热门问题