Pandas 是 Python 的核心数据分析支持库,提供了快速、灵活、明确的数据结构,旨在简单、直观地处理关系型、标记型数据。Pandas 的目标是成为 Python 数据分析实践与实战的必备高级工具,其长远目标是成为最强大、最灵活、可以支持任何语言的开源数据分析工具。经过多年不懈的努力,Pandas 离这个目标已经越来越近了。
Pandas 适用于处理以下类型的数据:

  • 与 SQL 或 Excel 表类似的,含异构列的表格数据;
  • 有序和无序(非固定频率)的时间序列数据;
  • 带行列标签的矩阵数据,包括同构或异构型数据;
  • 任意其它形式的观测、统计数据集, 数据转入 Pandas 数据结构时不必事先标记。

image.png

数据结构

维数 名称 描述
1 Series 带标签的一维同构数组
2 DataFrame 带标签的,大小可变的,二维异构表格

Series数据结构

  1. # Series 是带有标签的一维数组,可以保存任何数据类型(整数,字符串,浮点数,Python对象等),轴标签统称为索引
  2. import numpy as np
  3. import pandas as pd
  4. # 导入numpy、pandas模块
  5. ar = np.random.rand(5)
  6. print(ar)
  7. s = pd.Series(ar)
  8. print(s)
  9. print(type(s))
  10. # 查看数据、数据类型
  11. print(s.index,type(s.index))
  12. print(s.values,type(s.values))
  13. # .index查看series索引,类型为rangeindex
  14. # .values查看series值,类型是ndarray
  15. # 核心:series相比于ndarray,是一个自带索引index的数组 → 一维数组 + 对应索引
  16. # 所以当只看series的值的时候,就是一个ndarray
  17. # series和ndarray较相似,索引切片功能差别不大
  18. # series和dict相比,series更像一个有顺序的字典(dict本身不存在顺序),其索引原理与字典相似(一个用key,一个用index)
  19. ------------------------------------
  20. [0.57879139 0.74160843 0.96094125 0.51813092 0.47592715]
  21. 0 0.578791
  22. 1 0.741608
  23. 2 0.960941
  24. 3 0.518131
  25. 4 0.475927
  26. dtype: float64
  27. <class 'pandas.core.series.Series'>
  28. RangeIndex(start=0, stop=5, step=1) <class 'pandas.core.indexes.range.RangeIndex'>
  29. [0.57879139 0.74160843 0.96094125 0.51813092 0.47592715] <class 'numpy.ndarray'>

创建数据

pd.Series()
参数

  • data : 类似数组的、可迭代的、dict或标量值包含按序列存储的数据。
  • index: 类数组或索引(1d)

值必须是hashable和有相同的长度的“数据”。允许使用非唯一索引值。将默认为RangeIndex(0,1,2,…, n)如果未提供。如果字典和索引都是,则索引将覆盖在字典

  • dtype:
  • name:name为Series的一个参数,创建一个数组的 名称
  • copy:


  1. # Series 名称属性:name
  2. s1 = pd.Series(np.random.randn(5))
  3. print(s1)
  4. print('-----')
  5. s2 = pd.Series(np.random.randn(5),name = 'test')
  6. print(s2)
  7. print(s1.name, s2.name,type(s2.name))
  8. # name为Series的一个参数,创建一个数组的 名称
  9. # .name方法:输出数组的名称,输出格式为str,如果没用定义输出名称,输出为None
  10. s3 = s2.rename('hehehe')
  11. print(s3)
  12. print(s3.name, s2.name)
  13. # .rename()重命名一个数组的名称,并且新指向一个数组,原数组不变
  14. --------------------------------------
  15. 0 -0.403084
  16. 1 1.369383
  17. 2 1.134319
  18. 3 -0.635050
  19. 4 1.680211
  20. dtype: float64
  21. -----
  22. 0 -0.120014
  23. 1 1.967648
  24. 2 1.142626
  25. 3 0.234079
  26. 4 0.761357
  27. Name: test, dtype: float64
  28. None test <class 'str'>
  29. 0 -0.120014
  30. 1 1.967648
  31. 2 1.142626
  32. 3 0.234079
  33. 4 0.761357
  34. Name: hehehe, dtype: float64
  35. hehehe test

Series 创建方法一:由字典创建,字典的key就是index,values就是values

  1. dic = {'a':1 ,'b':2 , 'c':3, '4':4, '5':5}
  2. s = pd.Series(dic)
  3. print(s)
  4. # 注意:key肯定是字符串,假如values类型不止一个会怎么样? → dic = {'a':1 ,'b':'hello' , 'c':3, '4':4, '5':5}
  5. -------------------------------------
  6. 4 4
  7. 5 5
  8. a 1
  9. b 2
  10. c 3
  11. dtype: int64

Series 创建方法二:由数组创建(一维数组)

  1. arr = np.random.randn(5)
  2. s = pd.Series(arr)
  3. print(arr)
  4. print(s)
  5. # 默认index是从0开始,步长为1的数字
  6. s = pd.Series(arr, index = ['a','b','c','d','e'],dtype = np.object)
  7. print(s)
  8. # index参数:设置index,长度保持一致
  9. # dtype参数:设置数值类型
  10. -------------------------------------
  11. [ 0.11206121 0.1324684 0.59930544 0.34707543 -0.15652941]
  12. 0 0.112061
  13. 1 0.132468
  14. 2 0.599305
  15. 3 0.347075
  16. 4 -0.156529
  17. dtype: float64
  18. a 0.112061
  19. b 0.132468
  20. c 0.599305
  21. d 0.347075
  22. e -0.156529
  23. dtype: object

Series 创建方法三:由标量创建

  1. s = pd.Series(10, index = range(4))
  2. print(s)
  3. # 如果data是标量值,则必须提供索引。该值会重复,来匹配索引的长度
  4. ---------------------------
  5. 0 10
  6. 1 10
  7. 2 10
  8. 3 10
  9. dtype: int64


下标索引

位置下标,类似序列

  1. s = pd.Series(np.random.rand(5))
  2. print(s)
  3. print(s[0],type(s[0]),s[0].dtype)
  4. print(float(s[0]),type(float(s[0])))
  5. #print(s[-1])
  6. # 位置下标从0开始
  7. # 输出结果为numpy.float格式,
  8. # 可以通过float()函数转换为python float格式
  9. # numpy.float与float占用字节不同
  10. # s[-1]结果如何?
  11. -----------------------------
  12. 0 0.924575
  13. 1 0.988654
  14. 2 0.426333
  15. 3 0.216504
  16. 4 0.453570
  17. dtype: float64
  18. 0.924575004833 <class 'numpy.float64'> float64
  19. 0.9245750048328816 <class 'float'>

标签索引

  1. #
  2. s = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
  3. print(s)
  4. print(s['a'],type(s['a']),s['a'].dtype)
  5. # 方法类似下标索引,用[]表示,内写上index,注意index是字符串
  6. sci = s[['a','b','e']]
  7. print(sci,type(sci))
  8. # 如果需要选择多个标签的值,用[[]]来表示(相当于[]中包含一个列表)
  9. # 多标签索引结果是新的数组
  10. --------------------------
  11. a 0.714630
  12. b 0.213957
  13. c 0.172188
  14. d 0.972158
  15. e 0.875175
  16. dtype: float64
  17. 0.714630383451 <class 'numpy.float64'> float64
  18. a 0.714630
  19. b 0.213957
  20. e 0.875175
  21. dtype: float64 <class 'pandas.core.series.Series'>

切片索引

  1. s1 = pd.Series(np.random.rand(5))
  2. s2 = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
  3. print(s1[1:4],s1[4])
  4. print(s2['a':'c'],s2['c'])
  5. print(s2[0:3],s2[3])
  6. print('-----')
  7. # 注意:用index做切片是末端包含
  8. print(s2[:-1])
  9. print(s2[::2])
  10. # 下标索引做切片,和list写法一样
  11. -----------------------------------
  12. 1 0.865967
  13. 2 0.114500
  14. 3 0.369301
  15. dtype: float64 0.411702342342
  16. a 0.717378
  17. b 0.642561
  18. c 0.391091
  19. dtype: float64 0.39109096261
  20. a 0.717378
  21. b 0.642561
  22. c 0.391091
  23. dtype: float64 0.998978363818
  24. -----
  25. a 0.717378
  26. b 0.642561
  27. c 0.391091
  28. d 0.998978
  29. dtype: float64
  30. a 0.717378
  31. c 0.391091
  32. e 0.957639
  33. dtype: float64

布尔索引

  1. s = pd.Series(np.random.rand(3)*100)
  2. s[4] = None # 添加一个空值
  3. print(s)
  4. bs1 = s > 50
  5. bs2 = s.isnull()
  6. bs3 = s.notnull()
  7. print(bs1, type(bs1), bs1.dtype)
  8. print(bs2, type(bs2), bs2.dtype)
  9. print(bs3, type(bs3), bs3.dtype)
  10. print('-----')
  11. # 数组做判断之后,返回的是一个由布尔值组成的新的数组
  12. # .isnull() / .notnull() 判断是否为空值 (None代表空值,NaN代表有问题的数值,两个都会识别为空值)
  13. print(s[s > 50])
  14. print(s[bs3])
  15. # 布尔型索引方法:用[判断条件]表示,其中判断条件可以是 一个语句,或者是 一个布尔型数组!
  16. --------------------------------------
  17. 0 2.03802
  18. 1 40.3989
  19. 2 25.2001
  20. 4 None
  21. dtype: object
  22. 0 False
  23. 1 False
  24. 2 False
  25. 4 False
  26. dtype: bool <class 'pandas.core.series.Series'> bool
  27. 0 False
  28. 1 False
  29. 2 False
  30. 4 True
  31. dtype: bool <class 'pandas.core.series.Series'> bool
  32. 0 True
  33. 1 True
  34. 2 True
  35. 4 False
  36. dtype: bool <class 'pandas.core.series.Series'> bool
  37. -----
  38. Series([], dtype: object)
  39. 0 2.03802
  40. 1 40.3989
  41. 2 25.2001
  42. dtype: object

数据查看

重新索引reindex

numpy.reindex将会根据索引重新排序,如果当前索引不存在,则引入缺失值

  1. s = pd.Series(np.random.rand(3), index = ['a','b','c'])
  2. print(s)
  3. s1 = s.reindex(['c','b','a','d'])
  4. print(s1)
  5. # .reindex()中也是写列表
  6. # 这里'd'索引不存在,所以值为NaN
  7. s2 = s.reindex(['c','b','a','d'], fill_value = 0)
  8. print(s2)
  9. # fill_value参数:填充缺失值的值
  10. -----------------------------------
  11. a 0.343718
  12. b 0.322228
  13. c 0.746720
  14. dtype: float64
  15. c 0.746720
  16. b 0.322228
  17. a 0.343718
  18. d NaN
  19. dtype: float64
  20. c 0.746720
  21. b 0.322228
  22. a 0.343718
  23. d 0.000000
  24. dtype: float64

Series对齐

  1. s1 = pd.Series(np.random.rand(3), index = ['Jack','Marry','Tom'])
  2. s2 = pd.Series(np.random.rand(3), index = ['Wang','Jack','Marry'])
  3. print(s1)
  4. print(s2)
  5. print(s1+s2)
  6. # Series 和 ndarray 之间的主要区别是,Series 上的操作会根据标签自动对齐
  7. # index顺序不会影响数值计算,以标签来计算
  8. # 空值和任何值计算结果扔为空值
  9. --------------------------------------
  10. Jack 0.753732
  11. Marry 0.180223
  12. Tom 0.283704
  13. dtype: float64
  14. Wang 0.309128
  15. Jack 0.533997
  16. Marry 0.626126
  17. dtype: float64
  18. Jack 1.287729
  19. Marry 0.806349
  20. Tom NaN
  21. Wang NaN
  22. dtype: float64

删除Drop

  1. s = pd.Series(np.random.rand(5), index = list('ngjur'))
  2. print(s)
  3. s1 = s.drop('n')
  4. s2 = s.drop(['g','j'])
  5. print(s1)
  6. print(s2)
  7. print(s)
  8. # drop 删除元素之后返回副本(inplace=False)
  9. ----------------------------------------
  10. n 0.876587
  11. g 0.594053
  12. j 0.628232
  13. u 0.360634
  14. r 0.454483
  15. dtype: float64
  16. g 0.594053
  17. j 0.628232
  18. u 0.360634
  19. r 0.454483
  20. dtype: float64
  21. n 0.876587
  22. u 0.360634
  23. r 0.454483
  24. dtype: float64
  25. n 0.876587
  26. g 0.594053
  27. j 0.628232
  28. u 0.360634
  29. r 0.454483
  30. dtype: float64


添加

  1. s1 = pd.Series(np.random.rand(5))
  2. s2 = pd.Series(np.random.rand(5), index = list('ngjur'))
  3. print(s1)
  4. print(s2)
  5. s1[5] = 100
  6. s2['a'] = 100
  7. print(s1)
  8. print(s2)
  9. print('-----')
  10. # 直接通过下标索引/标签index添加值
  11. s3 = s1.append(s2)
  12. print(s3)
  13. print(s1)
  14. # 通过.append方法,直接添加一个数组
  15. # .append方法生成一个新的数组,不改变之前的数组
  16. ----------------------------------
  17. 0 0.516447
  18. 1 0.699382
  19. 2 0.469513
  20. 3 0.589821
  21. 4 0.402188
  22. dtype: float64
  23. n 0.615641
  24. g 0.451192
  25. j 0.022328
  26. u 0.977568
  27. r 0.902041
  28. dtype: float64
  29. 0 0.516447
  30. 1 0.699382
  31. 2 0.469513
  32. 3 0.589821
  33. 4 0.402188
  34. 5 100.000000
  35. dtype: float64
  36. n 0.615641
  37. g 0.451192
  38. j 0.022328
  39. u 0.977568
  40. r 0.902041
  41. a 100.000000
  42. dtype: float64
  43. -----
  44. 0 0.516447
  45. 1 0.699382
  46. 2 0.469513
  47. 3 0.589821
  48. 4 0.402188
  49. 5 100.000000
  50. n 0.615641
  51. g 0.451192
  52. j 0.022328
  53. u 0.977568
  54. r 0.902041
  55. a 100.000000
  56. dtype: float64
  57. 0 0.516447
  58. 1 0.699382
  59. 2 0.469513
  60. 3 0.589821
  61. 4 0.402188
  62. 5 100.000000
  63. dtype: float64

修改

  1. s = pd.Series(np.random.rand(3), index = ['a','b','c'])
  2. print(s)
  3. s['a'] = 100
  4. s[['b','c']] = 200
  5. print(s)
  6. # 通过索引直接修改,类似序列
  7. ----------------------------
  8. a 0.873604
  9. b 0.244707
  10. c 0.888685
  11. dtype: float64
  12. a 100.0
  13. b 200.0
  14. c 200.0
  15. dtype: float64

DataFrame

Dataframe 数据结构
Dataframe是一个表格型的数据结构,“带有标签的二维数组”。
Dataframe带有index(行标签)和columns(列标签)

  1. data = {'name':['Jack','Tom','Mary'],
  2. 'age':[18,19,20],
  3. 'gender':['m','m','w']}
  4. frame = pd.DataFrame(data)
  5. print(frame)
  6. print(type(frame))
  7. print(frame.index,'\n该数据类型为:',type(frame.index))
  8. print(frame.columns,'\n该数据类型为:',type(frame.columns))
  9. print(frame.values,'\n该数据类型为:',type(frame.values))
  10. # 查看数据,数据类型为dataframe
  11. # .index查看行标签
  12. # .columns查看列标签
  13. # .values查看值,数据类型为ndarray
  14. -----------------------------------------------
  15. age gender name
  16. 0 18 m Jack
  17. 1 19 m Tom
  18. 2 20 w Mary
  19. <class 'pandas.core.frame.DataFrame'>
  20. RangeIndex(start=0, stop=3, step=1)
  21. 该数据类型为: <class 'pandas.indexes.range.RangeIndex'>
  22. Index(['age', 'gender', 'name'], dtype='object')
  23. 该数据类型为: <class 'pandas.indexes.base.Index'>
  24. [[18 'm' 'Jack']
  25. [19 'm' 'Tom']
  26. [20 'w' 'Mary']]
  27. 该数据类型为: <class 'numpy.ndarray'>

基本查询

image.png

排序

语法

  1. df.sort_values(by="Count_AnimalName",ascending=True)

by为以Count_AnimalName名字的列排序 ascending:排列顺序,默认为True升序,反之为降序

索引

选择行与列

取行或列的注意

  • 方括号写数组,表示取行,对行进行操作
  • 方括号写字符串,表示的取列索引,对列进行操作

还有更多的经过pandas优化过的选择方式:

  • df.loc 通过标签索引行数据
  • df.iloc 通过位置获取行数据赋值更改数据的过程: ```python df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
    1. index = ['one','two','three'],
    2. columns = ['a','b','c','d'])
    print(df) print(‘——-‘)

data1 = df[‘a’] data2 = df[[‘a’,’c’]] print(data1,type(data1)) print(data2,type(data2)) print(‘——-‘)

按照列名选择列,只选择一列输出Series,选择多列输出Dataframe

data3 = df.loc[‘one’] data4 = df.loc[[‘one’,’two’]] print(data2,type(data3)) print(data3,type(data4))

按照index选择行,只选择一行输出Series,选择多行输出Dataframe


  1. a b c d

one 72.615321 49.816987 57.485645 84.226944 two 46.295674 34.480439 92.267989 17.111412

three 14.699591 92.754997 39.683577 93.255880

one 72.615321 two 46.295674 three 14.699591 Name: a, dtype: float64 a c one 72.615321 57.485645 two 46.295674 92.267989

three 14.699591 39.683577

  1. a c

one 72.615321 57.485645 two 46.295674 92.267989 three 14.699591 39.683577 a 72.615321 b 49.816987 c 57.485645 d 84.226944 Name: one, dtype: float64

  1. <a name="PJjUO"></a>
  2. #### df[] - 选择列
  3. 一般用于选择列,也可以选择行
  4. ```python
  5. df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
  6. index = ['one','two','three'],
  7. columns = ['a','b','c','d'])
  8. print(df)
  9. print('-----')
  10. data1 = df['a']
  11. data2 = df[['b','c']] # 尝试输入 data2 = df[['b','c','e']]
  12. print(data1)
  13. print(data2)
  14. # df[]默认选择列,[]中写列名(所以一般数据colunms都会单独制定,不会用默认数字列名,以免和index冲突)
  15. # 单选列为Series,print结果为Series格式
  16. # 多选列为Dataframe,print结果为Dataframe格式
  17. data3 = df[:1]
  18. #data3 = df[0]
  19. #data3 = df['one']
  20. print(data3,type(data3))
  21. # df[]中为数字时,默认选择行,且只能进行切片的选择,不能单独选择(df[0])
  22. # 输出结果为Dataframe,即便只选择一行
  23. # df[]不能通过索引标签名来选择行(df['one'])
  24. # 核心笔记:df[col]一般用于选择列,[]中写列名
  25. -----------------------------------
  26. a b c d
  27. one 88.490183 93.588825 1.605172 74.610087
  28. two 45.905361 49.257001 87.852426 97.490521
  29. three 95.801001 97.991028 74.451954 64.290587
  30. -----
  31. one 88.490183
  32. two 45.905361
  33. three 95.801001
  34. Name: a, dtype: float64
  35. b c
  36. one 93.588825 1.605172
  37. two 49.257001 87.852426
  38. three 97.991028 74.451954
  39. a b c d
  40. one 88.490183 93.588825 1.605172 74.610087 <class 'pandas.core.frame.DataFrame'>

df.loc[] - 按index选择行

  1. df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
  2. index = ['one','two','three','four'],
  3. columns = ['a','b','c','d'])
  4. df2 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
  5. columns = ['a','b','c','d'])
  6. print(df1)
  7. print(df2)
  8. print('-----')
  9. data1 = df1.loc['one']
  10. data2 = df2.loc[1]
  11. print(data1)
  12. print(data2)
  13. print('单标签索引\n-----')
  14. # 单个标签索引,返回Series
  15. data3 = df1.loc[['two','three','five']]
  16. data4 = df2.loc[[3,2,1]]
  17. print(data3)
  18. print(data4)
  19. print('多标签索引\n-----')
  20. # 多个标签索引,如果标签不存在,则返回NaN
  21. # 顺序可变
  22. data5 = df1.loc['one':'three']
  23. data6 = df2.loc[1:3]
  24. print(data5)
  25. print(data6)
  26. print('切片索引')
  27. # 可以做切片对象
  28. # 末端包含
  29. # 核心笔记:df.loc[label]主要针对index选择行,同时支持指定index,及默认数字index
  30. --------------------------------
  31. a b c d
  32. one 73.070679 7.169884 80.820532 62.299367
  33. two 34.025462 77.849955 96.160170 55.159017
  34. three 27.897582 39.595687 69.280955 49.477429
  35. four 76.723039 44.995970 22.408450 23.273089
  36. a b c d
  37. 0 93.871055 28.031989 57.093181 34.695293
  38. 1 22.882809 47.499852 86.466393 86.140909
  39. 2 80.840336 98.120735 84.495414 8.413039
  40. 3 59.695834 1.478707 15.069485 48.775008
  41. -----
  42. a 73.070679
  43. b 7.169884
  44. c 80.820532
  45. d 62.299367
  46. Name: one, dtype: float64
  47. a 22.882809
  48. b 47.499852
  49. c 86.466393
  50. d 86.140909
  51. Name: 1, dtype: float64
  52. 单标签索引
  53. -----
  54. a b c d
  55. two 34.025462 77.849955 96.160170 55.159017
  56. three 27.897582 39.595687 69.280955 49.477429
  57. five NaN NaN NaN NaN
  58. a b c d
  59. 3 59.695834 1.478707 15.069485 48.775008
  60. 2 80.840336 98.120735 84.495414 8.413039
  61. 1 22.882809 47.499852 86.466393 86.140909
  62. 多标签索引
  63. -----
  64. a b c d
  65. one 73.070679 7.169884 80.820532 62.299367
  66. two 34.025462 77.849955 96.160170 55.159017
  67. three 27.897582 39.595687 69.280955 49.477429
  68. a b c d
  69. 1 22.882809 47.499852 86.466393 86.140909
  70. 2 80.840336 98.120735 84.495414 8.413039
  71. 3 59.695834 1.478707 15.069485 48.775008
  72. 切片索引

df.iloc[] - 按照整数位置(从轴的0到length-1)选择行

类似list的索引,其顺序就是dataframe的整数位置,从0开始计

  1. df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
  2. index = ['one','two','three','four'],
  3. columns = ['a','b','c','d'])
  4. print(df)
  5. print('------')
  6. print(df.iloc[0])
  7. print(df.iloc[-1])
  8. #print(df.iloc[4])
  9. print('单位置索引\n-----')
  10. # 单位置索引
  11. # 和loc索引不同,不能索引超出数据行数的整数位置
  12. print(df.iloc[[0,2]])
  13. print(df.iloc[[3,2,1]])
  14. print('多位置索引\n-----')
  15. # 多位置索引
  16. # 顺序可变
  17. print(df.iloc[1:3])
  18. print(df.iloc[::2])
  19. print('切片索引')
  20. # 切片索引
  21. # 末端不包含
  22. ---------------------------------------
  23. a b c d
  24. one 21.848926 2.482328 17.338355 73.014166
  25. two 99.092794 0.601173 18.598736 61.166478
  26. three 87.183015 85.973426 48.839267 99.930097
  27. four 75.007726 84.208576 69.445779 75.546038
  28. ------
  29. a 21.848926
  30. b 2.482328
  31. c 17.338355
  32. d 73.014166
  33. Name: one, dtype: float64
  34. a 75.007726
  35. b 84.208576
  36. c 69.445779
  37. d 75.546038
  38. Name: four, dtype: float64
  39. 单位置索引
  40. -----
  41. a b c d
  42. one 21.848926 2.482328 17.338355 73.014166
  43. three 87.183015 85.973426 48.839267 99.930097
  44. a b c d
  45. four 75.007726 84.208576 69.445779 75.546038
  46. three 87.183015 85.973426 48.839267 99.930097
  47. two 99.092794 0.601173 18.598736 61.166478
  48. 多位置索引
  49. -----
  50. a b c d
  51. two 99.092794 0.601173 18.598736 61.166478
  52. three 87.183015 85.973426 48.839267 99.930097
  53. a b c d
  54. one 21.848926 2.482328 17.338355 73.014166
  55. three 87.183015 85.973426 48.839267 99.930097
  56. 切片索引

布尔型索引

和Series原理相同

  1. df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
  2. index = ['one','two','three','four'],
  3. columns = ['a','b','c','d'])
  4. print(df)
  5. print('------')
  6. b1 = df < 20
  7. print(b1,type(b1))
  8. print(df[b1]) # 也可以书写为 df[df < 20]
  9. print('------')
  10. # 不做索引则会对数据每个值进行判断
  11. # 索引结果保留 所有数据:True返回原数据,False返回值为NaN
  12. b2 = df['a'] > 50
  13. print(b2,type(b2))
  14. print(df[b2]) # 也可以书写为 df[df['a'] > 50]
  15. print('------')
  16. # 单列做判断
  17. # 索引结果保留 单列判断为True的行数据,包括其他列
  18. b3 = df[['a','b']] > 50
  19. print(b3,type(b3))
  20. print(df[b3]) # 也可以书写为 df[df[['a','b']] > 50]
  21. print('------')
  22. # 多列做判断
  23. # 索引结果保留 所有数据:True返回原数据,False返回值为NaN
  24. b4 = df.loc[['one','three']] < 50
  25. print(b4,type(b4))
  26. print(df[b4]) # 也可以书写为 df[df.loc[['one','three']] < 50]
  27. print('------')
  28. # 多行做判断
  29. # 索引结果保留 所有数据:True返回原数据,False返回值为NaN
  30. -------------------------------
  31. a b c d
  32. one 19.185849 20.303217 21.800384 45.189534
  33. two 50.105112 28.478878 93.669529 90.029489
  34. three 35.496053 19.248457 74.811841 20.711431
  35. four 24.604478 57.731456 49.682717 82.132866
  36. ------
  37. a b c d
  38. one True False False False
  39. two False False False False
  40. three False True False False
  41. four False False False False <class 'pandas.core.frame.DataFrame'>
  42. a b c d
  43. one 19.185849 NaN NaN NaN
  44. two NaN NaN NaN NaN
  45. three NaN 19.248457 NaN NaN
  46. four NaN NaN NaN NaN
  47. ------
  48. one False
  49. two True
  50. three False
  51. four False
  52. Name: a, dtype: bool <class 'pandas.core.series.Series'>
  53. a b c d
  54. two 50.105112 28.478878 93.669529 90.029489
  55. ------
  56. a b
  57. one False False
  58. two True False
  59. three False False
  60. four False True <class 'pandas.core.frame.DataFrame'>
  61. a b c d
  62. one NaN NaN NaN NaN
  63. two 50.105112 NaN NaN NaN
  64. three NaN NaN NaN NaN
  65. four NaN 57.731456 NaN NaN
  66. ------
  67. a b c d
  68. one True True True True
  69. three True True False True <class 'pandas.core.frame.DataFrame'>
  70. a b c d
  71. one 19.185849 20.303217 21.800384 45.189534
  72. two NaN NaN NaN NaN
  73. three 35.496053 19.248457 NaN 20.711431
  74. four NaN NaN NaN NaN
  75. ------

多重索引:比如同时索引行和列

先选择列再选择行 —— 相当于对于一个数据,先筛选字段,再选择数据量