版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HQ1356466973/article/details/83588739
假设我们想分析2017年和2018年广东,广西,湖南的人口数。如果使用Series进行存储的话,比较直接的方法如下:
In[1]index = [('广东',2017),('广东',2018),('广西', 2017),('广西', 2018),('湖
南',2017),('湖南', 2018)]
In[2]populations = [3387964,658964,
458752,698256,
125874,658963]
In[3]pop = pd.Series(populations, index=index)
In[4]pop
out[0]
(广东, 2017) 3387964
(广东, 2018) 658964
(广西, 2017) 458752
(广西, 2018) 698256
(湖南, 2017) 125874
(湖南, 2018) 658963
dtype: int64
通过切片获取数据:
In [9]: pop[('广东',2017):('广西', 2017)]
Out[9]:
(广东, 2017) 3387964
(广东, 2018) 658964
(广西, 2017) 458752
dtype: int64
但是这种做法不方便,假设我想获取2017年这三个省份的人口数,不得不采用复杂的办法:
In [12]: pop[[i for i in pop.index if i[1]==2017]]
Out[12]:
(广东, 2017) 3387964
(广西, 2017) 458752
(湖南, 2017) 125874
dtype: int64
这么做虽然也能达到所要的结果,但是与pandas让人崇拜又喜欢的切片相比,这种做法不够简洁、直观。而多级索引可以解决这个问题:
我们使用pandas中MultiIndex创建多级索引:
In [13]: index = pd.MultiIndex.from_tuples(index)
In [14]: index
Out[14]:
MultiIndex(levels=[['广东', '广西', '湖南'], [2017, 2018]],
labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])
MultiIndex里有一个标签表示索引的等级,于是我们将前面创建的pop的索引重置:
In [15]: pop = pop.reindex(index)
In [16]: pop
Out[16]:
广东 2017 3387964
2018 658964
广西 2017 458752
2018 698256
湖南 2017 125874
2018 658963
dtype: int64
如上图所示,其中前两列表示多级索引,第三列是数据。此时,我们可以通过切片很方便的获取2017的人口数:
In [17]: pop[:,2017]
Out[17]:
广东 3387964
广西 458752
湖南 125874
dtype: int64
注意到没有,其实上面的pop完全可以用一个表格来表示,也就是转换成一个DataFrame:
In [18]: pop_df = pop.unstack()
Out[18]:pop_df
2017 2018
广东 3387964 658964
广西 458752 698256
湖南 125874 658963
与unstack()相反的操作是stack():
In [22]: pop_df.stack()
Out[22]:
广东 2017 3387964
2018 658964
广西 2017 458752
2018 698256
湖南 2017 125874
2018 658963
dtype: int64
扫描二维码关注公众号,回复:
3915025 查看本文章