<p>将自定义lambda函数与<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer">^{<cd2>}</a>中的<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">^{<cd1>}</a>一起使用:</p>
<pre><code>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}]}]
</code></pre>
<p>如果有多个列,则可选择:</p>
<pre><code>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)
</code></pre>
<p>在具有多个组的大型数据帧中的性能:</p>
<pre><code>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)
</code></pre>