Last active
November 22, 2023 00:58
-
-
Save karpanGit/d0b8b987eaca3db24b9d5fc4b2b25004 to your computer and use it in GitHub Desktop.
pandas: create a dictionary containing groups following a groupby operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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