比较数据透视表中的列并添加结果

时间:2018-08-24 13:31:05

标签: python dataframe pivot-table

我正在使用来自http://senegal.opendataforafrica.org/SNVS2015/vital-statistics-of-senegal-2015的塞内加尔人口的公开数据csv。将带有大熊猫的数据导入数据框(形状17568,7)。

JSON.parse()

然后做了

    region  regional-division   sex indicator                               Unit    Date    Value
0   Dakar   Total   Total       Populations (projection de 2008 à   2015)   Number  2008    2482294.0 
1   Dakar   Total   Total       Populations    (projection de 2008 à 2015)  Number  2009    2536959.0
2   Dakar   Total   Total       Populations (projection de 2008 à   2015)   Number  2010    2592191.0 
3   Dakar   Total   Total       Populations   (projection de 2008 à 2015)   Number  2011    2647751.0
4   Dakar   Total   Total       Populations (projection de 2008 à   2015)   Number  2012    2703203.0 
5   Dakar   Total   Total       Populations   (projection de 2008 à 2015)   Number  2013    2776787.0
6   Dakar   Total   Total       Populations (projection de 2008 à   2015)   Number  2014    2851556.0 
7   Dakar   Total   Total       Populations   (projection de 2008 à 2015)   Number  2015    2927422.0
8   Dakar   Total   Men         Populations (projection de 2008 à   2015)   Number  2008    1242463.0 
9   Dakar   Total   Men         Populations (projection   de 2008 à 2015)   Number  2009    1269764.0

最重要的是

total_population_condition = (population['sex'] == 'Total') & (population['regional-division'] == 'Total')
total_population = population[total_population_condition]

Pivot Table

现在的问题是:我想找到在2008年至2015年之间人口增长最高的5个地区,以及收缩率最高的5个地区。我试图使用“ 2008”值和“ 2015”值访问数据透视列,然后将后者划分为前者。然后将结果添加到数据框。没办法。我该怎么办?

更新:我只是想出了...

pivot_total_population = pd.pivot_table(total_population,values='Value',index=['region','sex'],columns='Date')

1 个答案:

答案 0 :(得分:0)

弄清楚答案(向新手推荐流程提示的gboffi;-))

# compute growth first per region
pivot_total_population['growth'] = 
pivot_total_population.iloc[:,7]/pivot_total_population.iloc[:,0]

# then determine which are top 10 growing regions in terms of total population
pivot_total_population.sort_values(['growth'],ascending=False).head(10)

# then determine which are top 10 shrinking regions in terms of total population
pivot_total_population.sort_values(['growth'],ascending=True).head(10)