1. 14pandas的层次索引与取值的新方法_笔记
    2. # pandas:层次索引
    3. # 在某一个方向拥有多个(两个及两个以上)索引级别
    4. # 通过层次化索引,pandas能够以较低维度形式处理高纬度的数据
    5. # 通过层次化索引,可以按照层次统计数据
    6. # 层次索引包括Series层次索引和DataFrame层次索引
    7. s1 = pd.Series(data=[99, 87, 76, 67, 99],
    8. index=[['2017', '2017', '2018', '2018', '2018'], ['dfy', 'lisi', 'dfy', 'lisi', 'zs']])
    9. # 数据透视表 用到层次索引
    10. df1 = pd.DataFrame({
    11. 'year': [2016, 2016, 2017, 2017, 2018],
    12. 'fruit': ['apple', 'banana', 'apple', 'banana', 'apple'],
    13. 'production': [2345, 3242, 5667, 2576, 2134],
    14. 'profits': [23.22, 76.89, 90.99, 78.22, 98.76],
    15. })
    16. # ix是比较老的方法 新方式是使用iloc loc
    17. # iloc 对下标值进行操作 Series与DataFrame都可以操作
    18. # loc 对索引值进行操作 Series与DataFrame都可以操作
    19. # 将数据进行归一 合并 数据有重复 类似合并单元格
    20. # 设置多个行索引 层次化索引
    21. # 根据层次化索引取值 此时可以理解为三维的
    22. # pandas:按照层次索引进行统计数据
    23. # print(df2.sum(level='year'))
    24. # print(df2.mean(level='fruit'))
    25. # 下面的level写了2个相当于是 并且的关系
    26. # print(df2.min(level=['year', 'fruit']))
    27. # -*- coding: utf-8 -*-
    28. __author__ = 'dongfangyao'
    29. __date__ = '2018/1/2 下午9:10'
    30. __product__ = 'PyCharm'
    31. __filename__ = 'pandas5'
    32. import pandas as pd
    33. print(pd.__version__)
    34. s1 = pd.Series(data=[99, 87, 76, 67, 99],
    35. index=[['2017', '2017', '2018', '2018', '2018'], ['dfy', 'lisi', 'dfy', 'lisi', 'zs']])
    36. # 数据透视表 用到层次索引
    37. print(s1)
    38. print(s1.iloc[1])
    39. print(s1.loc['2017', 'lisi'])
    40. df1 = pd.DataFrame({
    41. 'year': [2016, 2016, 2017, 2017, 2018],
    42. 'fruit': ['apple', 'banana', 'apple', 'banana', 'apple'],
    43. 'production': [2345, 3242, 5667, 2576, 2134],
    44. 'profits': [23.22, 76.89, 90.99, 78.22, 98.76],
    45. })
    46. print(df1)
    47. print('-----')
    48. df2 = df1.set_index(['year', 'fruit'])
    49. # df1.index = ['a', 'b', 'a', 'c', 'd']
    50. # print(df2)
    51. # print(df2.index)
    52. print('-----')
    53. # print(df2.sum(level='year'))
    54. # print(df2.mean(level='fruit'))
    55. # print(df2.sum(level=['year', 'fruit']))
    56. # 取值的新方法
    57. # print(df1['profits'][2])
    58. # print(df1.ix[2]['profits'])
    59. # iloc 对下标值进行操作
    60. print(df1.iloc[2, 2])
    61. # loc 对索引值进行操作
    62. print(df1.loc[2, 'profits'])
    63. 复制代码