qq_42691545
2021-10-14 22:46
采纳率: 0%
浏览 17

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):

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • CSDN专家-HGJ 2021-10-14 23:49

    可参考类似如下 操作:

    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)
    

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

    打赏 评论

相关推荐 更多相似问题