numpy reshape()用法

reshape()用于改变数组形状

导入numpy

import numpy as np

定义一个数组

X = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(X)

输出

[1 2 3 4 5 6 7 8]

reshape 成 2行4列

a = X.reshape(2, 4)
print(a)

输出

[[1 2 3 4]
 [5 6 7 8]]

reshape 成 1列 2列

b = X.reshape(-1, 1)
print(b)
c = X.reshape(-1, 2)
print(c)

输出

[[1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]]
[[1 2]
 [3 4]
 [5 6]
 [7 8]]

reshape 成 1行 2行

d = X.reshape(1, -1)
print(d)
e = X.reshape(2, -1)
print(e)

结果

[[1 2 3 4 5 6 7 8]]
[[1 2 3 4]
 [5 6 7 8]]

reshape函数生成的新数组和原始数组公用一个内存,也就是说,不管是改变新数组还是原始数组的元素,另一个数组也会随之改变:

X = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(X)
[1 2 3 4 5 6 7 8]
a = X.reshape(2, 4)
print(a)
[[1 2 3 4]
 [5 6 7 8]]
X[0] = 777
print(X)
[777   2   3   4   5   6   7   8]
print(a)
[[777   2   3   4]
 [  5   6   7   8]]

你可能感兴趣的:(numpy reshape()用法)