暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

跟我学Numpy

艺直婷你 2020-10-23
238


Numpy 索引、切片:

数组索引机制指的是用方括号([])加序号的形式引用单个数组元素,它的用处很多,比如抽取元素,选取数组的几个元素,甚至为其赋一个新值。

ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样

ndarray 数组可以基于 0 - n 的下标进行索引,切片对象可以通过内置的 slice 函数,并设置 start, stop 及 step 参数进行,从原数组中切割出一个新数组。

    import numpy as np
    a = np.arange(10)
    s = slice(2,7,2) # 从索引 2 开始到索引 7 停止,间隔为2
    print (a[s])


    [2  4  6]   #输出结果

    通过 arange() 函数创建 ndarray 对象。然后,分别设置起始,终止和步长的参数为 2,7 和 2。

    我们也可以通过冒号分隔切片参数 start:stop:step 来进行切片操作:

      import numpy as np 
      a = np.arange(10)
      b = a[2:7:2] # 从索引 2 开始到索引 7 停止,间隔为 2
      print(b)

      冒号

      如果只放置一个参数,如 [2],将返回与该索引相对应的单个元素。如果为 [2:],表示从该索引开始以后的所有项都将被提取。如果使用了两个参数,如 [2:7],那么则提取两个索引(不包括停止索引)之间的项。

        import numpy as np
        a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
        b = a[5]
        print(b)
        5  #输出结果

        例:

          import numpy as np
          a = np.arange(10)
          print(a[2:])
          [2  3  4  5  6  7  8  9]   #输出结果

          dots索引

          Numpy允许使用....表示足够多的冒号来构建完整的索引列表。

          比如,如果 x
           是 5 维数组:

          • x[1,2,...]
             等于 x[1,2,:,:,:]

          • x[...,3]
             等于 x[:,:,:,:,3]

          • x[4,...,5,:]
             等于 x[4,:,:,5,:]

            import numpy as np
            x = np.random.randint(1, 100, [2, 2, 3])
            print(x)
            # [[[ 5 64 75]
            # [57 27 31]]
            #
            # [[68 85 3]
            # [93 26 25]]]


            print(x[1, ...])
            # [[68 85 3]
            # [93 26 25]]


            print(x[..., 2])
            # [[75 31]
            #  [ 3 25]]

            省略号

            切片可以包括省略号.... ,来使选择元组的长度与数组的维度相同。如果在行位置使用省略号,它将返回包含行中元素的ndarray。

              import numpy as np

              a = np.array([[1,2,3],[3,4,5],[4,5,6]])
              print (a[...,1]) # 第2列元素
              print (a[1,...]) # 第2行元素
              print (a[...,1:]) # 第2列及剩下的所有元素
                [2 4 5]
                [3 4 5]
                [[2 3]
                [4 5]
                [5 6]]

                整数数组索引

                  import numpy as np


                  a=np.array([[1,2],[3,4],[5,6]])
                  b=a[0,0]
                  b=2
                  print(a[0,0]==b)
                  #False

                  布尔索引

                  通过一个布尔数组来索引目标数组。

                    import numpy as np


                    x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
                    y = x > 5
                    print(y)
                    # [False False False False False True True True]
                    print(x[x > 5])
                    # [6 7 8]


                    x = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
                    y = np.logical_not(np.isnan(x))
                    print(x[y])
                    # [1. 2. 3. 4. 5.]


                    x = np.array([[11, 12, 13, 14, 15],
                    [16, 17, 18, 19, 20],
                    [21, 22, 23, 24, 25],
                    [26, 27, 28, 29, 30],
                    [31, 32, 33, 34, 35]])
                    y = x > 25
                    print(y)
                    # [[False False False False False]
                    # [False False False False False]
                    # [False False False False False]
                    # [ True True True True True]
                    # [ True True True True True]]
                    print(x[x > 25])
                    # [26 27 28 29 30 31 32 33 34 35]


                    多维数组同上索引方法:

                      import numpy as np
                      a = np.array([[1,2,3],[3,4,5],[4,5,6]])
                      print(a)
                      # 从某个索引处开始切割
                      print('从数组索引 a[1:] 处开始切割')
                      print(a[1:])
                        [[1 2 3]       #结果输出
                        [3 4 5]
                        [4 5 6]]
                        从数组索引 a[1:] 处开始切割
                        [[3 4 5]
                        [4 5 6]]

                        副本与视图

                        Numpy 中,尤其是在做数组运算或数组操作时,返回结果不是数组的 副本 就是 视图。

                        Numpy 中,所有赋值运算不会为数组和数组中的任何元素创建副本。


                        • numpy.ndarray.copy() 函数创建一个副本。对副本数据进行修改,不会影响到原始数据,它们物理内存不在同一位置。

                          import numpy as np
                          x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
                          y = x
                          y[0] = -1
                          print(x)
                          # [-1 2 3 4 5 6 7 8]
                          print(y)
                          # [-1  2  3  4  5  6  7  8]
                          x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
                          y = x.copy()
                          y[0] = -1
                          print(x)
                          # [1 2 3 4 5 6 7 8]
                          print(y)
                          # [-1 2 3 4 5 6 7 8]

                          数组迭代

                          除了for循环,Numpy 还提供另外一种更为优雅的遍历方法。

                          • apply_along_axis(func1d, axis, arr)
                             Apply a function to 1-D slices along the given axis.

                            import numpy as np


                            x = np.array([[11, 12, 13, 14, 15],
                            [16, 17, 18, 19, 20],
                            [21, 22, 23, 24, 25],
                            [26, 27, 28, 29, 30],
                            [31, 32, 33, 34, 35]])


                            y = np.apply_along_axis(np.sum, 0, x)
                            print(y) # [105 110 115 120 125]
                            y = np.apply_along_axis(np.sum, 1, x)
                            print(y) # [ 65 90 115 140 165]


                            y = np.apply_along_axis(np.mean, 0, x)
                            print(y) # [21. 22. 23. 24. 25.]
                            y = np.apply_along_axis(np.mean, 1, x)
                            print(y) # [13. 18. 23. 28. 33.]




                            def my_func(x):
                            return (x[0] + x[-1]) * 0.5




                            y = np.apply_along_axis(my_func, 0, x)
                            print(y) # [21. 22. 23. 24. 25.]
                            y = np.apply_along_axis(my_func, 1, x)
                            print(y) # [13. 18. 23. 28. 33.]


                            参考:

                            https://github.com/datawhalechina/team-learning-program/blob/master/IntroductionToNumpy/task02%20%E7%B4%A2%E5%BC%95/05.%20%E7%B4%A2%E5%BC%95%E3%80%81%E5%88%87%E7%89%87%E4%B8%8E%E8%BF%AD%E4%BB%A3.ipynb

                            文章转载自艺直婷你,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                            评论