python - Can Pandas Groupby Aggregate into a List of Objects -
while panda's groupby
able aggregate data functions sum
, mean
, there way aggregate list of objects, keys of these objects corresponds column names these values aggregated from?
question:
if data looked this
b c 1 10 22 1 12 20 1 11 8 1 10 10 2 11 13 2 12 10 3 14 0
how can pandas transform hypothetical output:
d 1 [{'b':10, 'c':22}, {'b':12, 'c':20}, {'b':11, 'c':8}, {'b':10, 'c':10}] 2 [{'b':11, 'c':13}, {'b':12, 'c':10}] 3 [{'b':14, 'c':0}]
i wasn't sure work, seems to.
in [35]: df.groupby('a').apply(lambda x: x.to_dict(orient='records')) out[35]: 1 [{u'a': 1, u'c': 22, u'b': 10}, {u'a': 1, u'c'... 2 [{u'a': 2, u'c': 13, u'b': 11}, {u'a': 2, u'c'... 3 [{u'a': 3, u'c': 0, u'b': 14}] dtype: object
depending on you're trying accomplish may more natural iterate of groupby object , convert, this:
in [36]: a, df_gb in df.groupby('a'): ...: d = df_gb.to_dict(orient='records') ...:
Comments
Post a Comment