1运算符
>>> x=np.arange(0,10,2)
>>> x
array([0, 2, 4, 6, 8])
>>> x<3
array([ True, True, False, False, False])
>>> x>3
array([False, False, True, True, True])
>>> x<=3
array([ True, True, False, False, False])
>>> x>=3
array([False, False, True, True, True])
>>> x!=3
array([ True, True, True, True, True])
>>> x==3
array([False, False, False, False, False])
>>> x=3
>>> x
3
2.二维上面进行判断
>>> rng=np.random.RandomState(0)
>>> rng
RandomState(MT19937) at 0x7FD338D90888
>>> x=rng.randint(10,size=(3,4))
>>> x
array([[5, 0, 3, 3],
[7, 9, 3, 5],
[2, 4, 7, 6]])
>>> x<6
array([[ True, True, True, True],
[False, False, True, True],
[ True, True, False, False]])
3.操作布尔数组
统计记录的个数
首先生成一个随机的二维数组
>>> import numpy as np
>>> rng=np.random.RandomState(0)
>>> x=rng.randint(10,size=(3,4))
>>> x
array([[5, 0, 3, 3],
[7, 9, 3, 5],
[2, 4, 7, 6]])
统计数量:np.sum
>>> np.sum(x<6)
8
>>> np.sum(x<6,axis=1)
array([4, 2, 2])
是否存在:np.any
>>> np.any(x>8)
True
>>> np.any(x<0)
False
是否都是:np.all
>>> np.all(x<10)
True
>>> np.all(x==6)
False
>>> np.all(x<8,axis=1)
array([ True, False, True])
>>>
4.布尔运算符
>>>np.sum((inches>5)&(inches<1))
29
5.索引升级版
z不是array数组模块,报错不能用
>>> z = list(range(10))
>>> z
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> z[y]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only integer scalar arrays can be converted to a scalar index
>>> y
array([[3, 7],
[4, 5]])
x是array数组模块,可以用这个方法
>>> rand =np.random.RandomState(42)
>>> rand
RandomState(MT19937) at 0x7FBDFBACA990
>>> x=rand.randint(100,size=10)
>>> x
array([51, 92, 14, 71, 60, 20, 82, 86, 74, 74])
>>> x[y]
array([[71, 86],
[60, 20]])
6.索引升级版-二维
首先生成一个二维数组
>>> x=np.arange(12).reshape((3,4))
>>> x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
然后生成对应的行row,和列col的信息
>>> row=np.array([0,1,2])
>>> row
array([0, 1, 2])
>>> col=np.array([2,1,3])
>>> col
array([2, 1, 3])
取值
选取对应的坐标,此处的2是对应的(0,2),此处的5对应的(1,1),此处的11,对应的(2,3)
>>> x[row,col]
array([ 2, 5, 11])
拓展,同理
>>> x[row[:,np.newaxis],col]
array([[ 2, 1, 3],
[ 6, 5, 7],
[10, 9, 11]])
>>> row[:,np.newaxis],col
(array([[0],
[1],
[2]]), array([2, 1, 3]))
>>> row[:,np.newaxis]*col
array([[0, 0, 0],
[2, 1, 3],
[4, 2, 6]])
花哨的索引与简单索引的组合
第二行的,第三个数,第一个数,第二个数
>>> x[2,[2,0,1]]
array([10, 8, 9])
索引与切片的结合
第一行之后的,一次第三个,第一个,第二个
>>> x[1:,[2,0,1]]
array([[ 6, 4, 5],
[10, 8, 9]])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)