numpy学习

创建数组:

numpy.arange(start, stop, step, dtype)

参数描述
start 起始值,默认为0
stop 终止值(不包含)
step 步长,默认为1
dtype 返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

参数描述
start 序列的起始值
stop 序列的终止值,如果endpointtrue,该值包含于数列中
num 要生成的等步长的样本数量,默认为50
endpoint 该值为 true 时,数列中中包含stop值,反之不包含,默认是True。
retstep 如果为 True 时,生成的数组中会显示间距,反之不显示。
dtype ndarray 的数据类型

np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

base 参数意思是取对数的时候 log 的下标。

参数描述
start 序列的起始值为:base ** start
stop 序列的终止值为:base ** stop。如果endpointtrue,该值包含于数列中
num 要生成的等步长的样本数量,默认为50
endpoint 该值为 true 时,数列中中包含stop值,反之不包含,默认是True。
base 对数 log 的底数。
dtype ndarray 的数据类型

切片:

numpy 的数组切片时,和py的切片比较相似。但是由于不同维度的出现有一点点不同。

  a = np.arange(10)   # [0 1 2 3 4 5 6 7 8 9]

  a[2:5]  # [2 3 4]

  a[1,2,3,5,7]  # [1,2,3,5,7]

一维简单。

a = array([[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]])

  In [29]: a[2:5]
  Out[29]: array([[6, 7, 8]])

  In [30]: a[1,2]   # 索引为1的行,索引为2的列。 组合起来就是 5 这个值的位置
  Out[30]: 5

  In [31]: a[0:2,0:2]    #   
  Out[31]:
    array([[0, 1],
       [3, 4]])

还有一些特别的索引方式:

  布尔索引: 

  In [33]: a[a>5]
  Out[33]: array([6, 7, 8])

  

  In [34]: a[(a>5) & (a%2==0)]   #   &  这是一个位运算符  并不是单纯的and的意思。 所以这样用的时候,两个条件加 小括号
  Out[34]: array([6, 8])

  

  In [35]: a[(a>5) | (a%2==0)]   # | 也和平时的 or  不相同。 没有短路这一说。符合条件就可以
  Out[35]: array([0, 2, 4, 6, 7, 8])

  In [37]: a[(a>5) | ~(a%2==0)]  #  ~ 这个类似于  ! 取反
  Out[37]: array([1, 3, 5, 6, 7, 8])

原文地址:https://www.cnblogs.com/chengege/p/12576232.html