=== 层次索引 ===
1、多层索引 index
一组成绩:[89,99,56,44,33,56]
前三个2017年的语数英成绩
后三个2018的语数英成绩
deep_Series = pd.Series([89,99,56,44,33,56],index=[
[2017,2017,2017,2018,2018,2018],
list('CMECME')] )
print('\n--- deep_Series ---')
print(deep_Series)
print('\n--- 2017的数学成绩 ---')
print(deep_Series[2017,'M'])
print('\n--- 所有年份的语文恩成绩 ---')
print(deep_Series[:,'C'])
--- deep_Series ---
2017 C 89
M 99
E 56
2018 C 44
M 33
E 56
dtype: int64
--- 2017的数学成绩 ---
99
--- 所有年份的语文恩成绩 ---
2017 89
2018 44
dtype: int64
2、交换索引 swaplevel
print('\n--- 内外层索引交换 ---')
deep_Series = deep_Series.swaplevel()
deep_Series = deep_Series.sort_index()
print(deep_Series)
print('\n--- 所有年份的语文恩成绩 ---')
print(deep_Series['C'])
--- 内外层索引交换 ---
C 2017 89
2018 44
E 2017 56
2018 56
M 2017 99
2018 33
dtype: int64
--- 所有年份的语文恩成绩 ---
2017 89
2018 44
dtype: int64
=== 相互转换 ===
1、 转换成 DataFrame
print('\n--- deep_Series ---')
print(deep_Series)
print('\n--- 转换成 DataFrame ---')
# unstack (默认level=1)
data_frame = deep_Series.unstack(level = 0)
data_frame
2、 DataFrame 转回2层Serices
deep_Series = data_frame.stack()
deep_Series
2017 C 89
E 56
M 99
2018 C 44
E 56
M 33
dtype: int64
=== 多层Series算数统计 ===
1、 Series 计算2017年的总分(level=0 外层)
deep_Series.sum(level=0)
2017 244
2018 133
dtype: int64
2、 Series 计算各科成绩平均分(level=1 内层)
deep_Series.mean(level=1)
C 66.5
E 56.0
M 66.0
dtype: float64