import numpy as np
np.random.seed(0)
x = np.arange(10)
x
"""
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
X = np.arange(15).reshape((3, 5))
X
"""
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
"""
numpy.array 的基本属性
.ndim
.shape
.size
x.ndim # 1
x.shape # (10,)
x.size # 10
X.ndim # 2
X.shape # (3, 5)
X.size # 15
numpy.array 的数据访问
x # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[-1] # 9
x[:5] # array([0, 1, 2, 3, 4])
x[5:] # array([5, 6, 7, 8, 9])
x[::2] # array([0, 2, 4, 6, 8])
x[1::2] # array([1, 3, 5, 7, 9])
x[::-1] # array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
X
"""
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
"""
X[0,-1] # 4
X[:2, :3]
"""
array([[0, 1, 2],
[5, 6, 7]])
"""
X[:2, ::2]
"""
array([[0, 2, 4],
[5, 7, 9]])
"""
X[::-1, ::-1]
"""
array([[14, 13, 12, 11, 10],
[ 9, 8, 7, 6, 5],
[ 4, 3, 2, 1, 0]])
"""
X[0, :] # array([0, 1, 2, 3, 4])
X[:, 0] # array([ 0, 5, 10])
Subarray of numpy.array
X
"""
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
"""
subX = X[:2, :3]
subX
"""
array([[0, 1, 2],
[5, 6, 7]])
"""
subX[0, 0] = 100
subX
"""
array([[100, 1, 2],
[ 5, 6, 7]])
"""
X
"""
array([[100, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[ 10, 11, 12, 13, 14]])
"""
X
"""
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
"""
subX = X[:2, :3].copy()
subX[0, 0] = 100
subX
"""
array([[100, 1, 2],
[ 5, 6, 7]])
"""
X
"""
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
"""
Reshape
x # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x.shape # (10,)
x.ndim # 1
a = x.reshape(1,10)
a # array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
a.ndim # 2
a.shape # (1, 10)
b = x.reshape(2, 5)
b
"""
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
"""
b.shape # (2, 5)
b.ndim # 2
x.reshape(-1, 10)
"""
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
"""
x.reshape(10, -1)
"""
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
"""