I have a DataFrame:
dat = pd.DataFrame({
'key1' : [ 1, 1, 2, 2, 3, 3, 3, 3, 4, 4],
'key2' : ['a', 'b', 'a', 'c', 'b', 'c', 'd', 'e', 'c', 'e'],
'value' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
})
I could use list
to aggregate the columns:
dat.groupby('key1')['key2'].apply(list)
## key1
## 1 [a, b]
## 2 [a, c]
## 3 [b, c, d, e]
## 4 [c, e]
## Name: key2, dtype: object
What if I wanted to obtain an aggregate grouped by key1
, where each row is a dict
of { key2 : value }
pairs? My expected output is:
## key1
## 1 {a : 1, b : 2}
## 2 {a : 3, c : 4}
## 3 {b : 5, c : 6, d : 7, e : 8}
## 4 {c : 9, e : 10}
How can this be achieved in pandas?
One solution could be to create two lists using the function above and then combine them as dict
, but maybe there is a better solution?