Create separate dataframes by Iterate a groupby object

半世苍凉 提交于 2019-12-13 04:19:20

问题


Looking to loop through region column (4 regions) by using group by and then run a bunch of pivot tables which which I will stack on top of each other and create a total row. The pivot tables need to be run on all 4 regions i am grouping by. Once i have the pivots, i then need to stack those on top of each other.

import pandas as pd
import numpy as np

df = pd.DataFrame({'Roll': ['Analyst','doctor','activist','lawyer','writer','manager'], 
                   'Animal': ['cats','dogs','birds','pianos','elephant','dinos'], 
                   'Region': ['EM', 'US', 'US', 'Europe', 'Asia', 'Asia'], 
                   'Year': ['2006', '2010', '2013', '2010', '2002', '2003'], 
                   'Dollar Amount': [10, 20, 30, 40, 50, 60]})

years = ['2001', '2002', '2003', '2004', '2005']    

dfs = {}
for region, df_region in df.groupby('Region'):
    filter = df[df['Roll'].isin(Analyst) & df['Animal'].isin(cats) & df['Year'].isin(years)]
    pivot = pd.pivot_table(filter, index=['Animal'], columns='Year', 
                           values=['Dollar Amount'], aggfunc=np.sum, fill_value=0)

    filter2 = df[df['Roll'].isin(Analyst) & df['Animal'].isin(dogs) & df['Year'].isin(years)]
    pivot2 = pd.pivot_table(filter2, index=['Animal'], columns='Year', 
                            values=['Dollar Amount'], aggfunc=np.sum, fill_value=0)

    Total = pd.concat([pivot1, pivot2])
    Total = Total.append(Total.sum().rename('Analyst'))
    dfs[region] = df_region

All_regions = pd.concat(['df_US', 'df_EM', 'df_Europe', 'df_Asia'])

来源:https://stackoverflow.com/questions/53888636/create-separate-dataframes-by-iterate-a-groupby-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!