Last active
August 9, 2019 22:39
-
-
Save ttimbers/745084be69f1b1f68036dc8c1c58d0da to your computer and use it in GitHub Desktop.
Example of a simple function to create a nested data frame in python
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
import pandas as pd | |
from gapminder import gapminder | |
def nest(grouped_data): | |
'''Takes in a grouped data frame''' | |
groups = [] | |
datas = [] | |
for group in grouped_data.groups: | |
groups.append(group) | |
datas.append(grouped_data.get_group(group)) | |
if len(grouped_data.grouper.names) == 1: | |
return pd.DataFrame({grouped_data.grouper.names[0]: groups, 'data': datas}) | |
else: | |
temp = pd.DataFrame({'tmp' : groups}) | |
temp[grouped_data.grouper.names] = pd.DataFrame(temp['tmp'].tolist()) | |
del temp['tmp'] | |
temp['data'] = datas | |
return temp | |
# Examples | |
grouped = gapminder.groupby('continent') | |
test1 = nest(grouped) | |
test1 | |
double_group = gapminder.groupby(['continent', 'country']) | |
test2 = nest(double_group) | |
test2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment