机器学习 August 19, 2018

1-4 numpy中Fancy Indexing

Words count 4.5k Reading time 4 mins. Read count 0

import numpy as np
x = np.arange(16)
x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
x[3]
3
x[3:9]
array([3, 4, 5, 6, 7, 8])
x[3:9:2]
array([3, 5, 7])
[x[3],x[5],x[8]]
[3, 5, 8]
ind = [3,5,8]
x[ind]
array([3, 5, 8])
ind = np.array([[0,2],[1,3]])
x[ind]
array([[0, 2],
       [1, 3]])
X = x.reshape(4,-1)
X
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
row = np.array([0,1,2])
col = np.array([1,2,3])
X[row,col]
array([ 1,  6, 11])
X[0,col]
array([1, 2, 3])
X[:2,col]
array([[1, 2, 3],
       [5, 6, 7]])
col = [True,False,True,True]
X[1:3,col]
array([[ 4,  6,  7],
       [ 8, 10, 11]])

numpy.array的比较

x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
x <3
array([ True,  True,  True, False, False, False, False, False, False,
       False, False, False, False, False, False, False])
x > 3 
array([False, False, False, False,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True])
X <=3
array([[ True,  True,  True,  True],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]])
x>=3
array([False, False, False,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True])
x==3
array([False, False, False,  True, False, False, False, False, False,
       False, False, False, False, False, False, False])
2 * x == 24 - 4 * x
array([False, False, False, False,  True, False, False, False, False,
       False, False, False, False, False, False, False])
X
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
X < 6
array([[ True,  True,  True,  True],
       [ True,  True, False, False],
       [False, False, False, False],
       [False, False, False, False]])
x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
np.sum(x <=3)
4
# 只要有一个满足条件,就会返回true
np.any(x==0)
True
np.all(x>=0)
True
X
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
np.sum(X %2 ==0)
8
np.sum(X%2 ==0,axis = 0)
array([4, 0, 4, 0])
np.sum(X%2==0,axis = 1)
array([2, 2, 2, 2])
np.sum((x>3)&(x<10))
6
0%