Skip to content

Instantly share code, notes, and snippets.

@karpanGit
Last active November 22, 2023 00:58
Show Gist options
  • Save karpanGit/d0b8b987eaca3db24b9d5fc4b2b25004 to your computer and use it in GitHub Desktop.
Save karpanGit/d0b8b987eaca3db24b9d5fc4b2b25004 to your computer and use it in GitHub Desktop.
pandas: create a dictionary containing groups following a groupby operation
# pandas groupby, create a ditionary with groups using a comprehension
import pandas as pd
import numpy as np
df = pd.DataFrame({'key1': ['a','a','b','b','a'],
'key2': ['one', 'two', 'one', 'two', 'three'],
'data1': np.random.randn(5),
'data2': np.random.random(5)})
# by default the groupby selects all remaining columns
groups = df.groupby('key1')
res = {key1: group for key1, group in groups}
print(res['a'])
print(res['b'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment