python有关groupby相关的问题

分组的时候如何将一组数据作为行,一组数据作为列

img


将这个表用这种方式表达出来

img

population = pd.DataFrame({'ages':['under18','under18','total','under18','total', 'total', 'under18','total','under18','total'],
'year':[2012,2010,2010,2010,2012,2012,2010,2012,2012,2012],
'population':[11174,48175,98723,np.nan,11257,1140,23654,np.nan,1637,12653]}
)
population

def calculate_array(population):

可参考类似如下 操作:

import pandas as pd
import numpy as np
population = pd.DataFrame({'ages':['under18','under18','total','under18','total', 'total', 'under18','total','under18','total'],
'year':[2012,2010,2010,2010,2012,2012,2010,2012,2012,2012],
'population':[11174,48175,98723,np.nan,11257,1140,23654,np.nan,1637,12653]}
)
print(population)
a=population.groupby(['year','ages'])['population'].apply(sum).to_frame().reset_index()
print(a)
b = pd.pivot(index='year', columns='ages', values='population', data=a).reset_index()
b=b.rename_axis([''],axis=1).astype(int) 
print(b)

如对你有帮助,请采纳。点击我回答右上角【采纳】按钮。