机器学习 August 19, 2018

1-1 numpy数组合并

Words count 5.2k Reading time 5 mins. Read count 0

import numpy as np
x = np.array([1,2,3])
y = np.array([3,2,1])
x
array([1, 2, 3])
y
array([3, 2, 1])

x与y合并

np.concatenate([x,y])
array([1, 2, 3, 3, 2, 1])
z = np.array([666,666,666])
np.concatenate([x,y,z])
array([  1,   2,   3,   3,   2,   1, 666, 666, 666])

基于矩阵的操作

A = np.array([[1,2,3],
              [4,5,6]])
np.concatenate([A,A])
array([[1, 2, 3],
       [4, 5, 6],
       [1, 2, 3],
       [4, 5, 6]])
np.concatenate([A,A],axis = 1)
array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]])
np.concatenate([A,z])
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-14-abdc54b54f98> in <module>()
----> 1 np.concatenate([A,z])


ValueError: all the input arrays must have same number of dimensions
np.concatenate([A,z.reshape(1,-1)])
array([[  1,   2,   3],
       [  4,   5,   6],
       [666, 666, 666]])
A2 = np.concatenate([A,z.reshape(1,-1)])
A2
array([[  1,   2,   3],
       [  4,   5,   6],
       [666, 666, 666]])
np.vstack([A,z])
array([[  1,   2,   3],
       [  4,   5,   6],
       [666, 666, 666]])
B = np.full((2,2),100)
np.hstack([A,B])
array([[  1,   2,   3, 100, 100],
       [  4,   5,   6, 100, 100]])

分割

x = np.arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

将x分别从位置3和位置7进行分割

x1,x2,x3 = np.split(x,[3,7])
x1
array([0, 1, 2])
x2
array([3, 4, 5, 6])
x1,x2 = np.split(x,[5])
x1
array([0, 1, 2, 3, 4])
x2
array([5, 6, 7, 8, 9])
A = np.arange(16).reshape([4,4])
A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
A1,A2 = np.split(A,[2])
A1
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
A2
array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])
A1,A2 = np.split(A,[2],axis = 1)
A1
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]])
A2
array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]])
upper,lower = np.vsplit(A,[2])
upper
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
lower
array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])
left,right = np.hsplit(A,[2])
left
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]])
right
array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]])
data = np.arange(16).reshape((4,4))
data
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
x,y = np.hsplit(data,[-1])
x
array([[ 0,  1,  2],
       [ 4,  5,  6],
       [ 8,  9, 10],
       [12, 13, 14]])
y
array([[ 3],
       [ 7],
       [11],
       [15]])
y[:,0]
array([ 3,  7, 11, 15])
0%