a.reshape()

返回一个修改后的数组,但不会更改原始数组

#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
a = np.array([[3.0, 9.0, 8.0, 0.0],[1.0, 4.0, 6.0, 5.0],[1.0, 9.0, 3.0, 1.0]])
print(a)
'''
[[3. 9. 8. 0.]
 [1. 4. 6. 5.]
 [1. 9. 3. 1.]]'''
print(a.shape) # (3, 4)
# a.reshape(new_shape) 返回一个修改后的数组,但不会更改原始数组
print(a.reshape(2,6)) # [[3. 9. 8. 0. 1. 4.][6. 5. 1. 9. 3. 1.]] 两行,6列
print(a) #不会改变原始数组
'''
[[3. 9. 8. 0.]
 [1. 4. 6. 5.]
 [1. 9. 3. 1.]]'''

参数 -1 的用法

print(a.reshape(-1)) # [3. 9. 8. 0. 1. 4. 6. 5. 1. 9. 3. 1.]
print(a.reshape(-1).shape) # (12,) 等同于 a.flatten() 

print(a.reshape(1,-1)) # [[3. 9. 8. 0. 1. 4. 6. 5. 1. 9. 3. 1.]]
print(a.reshape(1,-1).shape) # (1, 12)

print(a.reshape(2,-1)) # [[3. 9. 8. 0. 1. 4.][6. 5. 1. 9. 3. 1.]]
print(a.reshape(2,-1).shape) # (2, 6)

print(a.reshape(-1,2)) # [[3. 9.][8. 0.][1. 4.][6. 5.][1. 9.][3. 1.]]
print(a.reshape(-1,2).shape) # (6, 2)

把2-D数组变成3-D数组

b = a.reshape(2,2,-1) 
print(b) # [[[3. 9. 8.][0. 1. 4.]] [[6. 5. 1.][9. 3. 1.]]]
print(b.shape) # (2, 2, 3)

reshape也可应用于3-D数组

print(b.reshape(-1)) # [3. 9. 8. 0. 1. 4. 6. 5. 1. 9. 3. 1.]
print(b.reshape(3,-1)) # [[3. 9. 8. 0.][1. 4. 6. 5.][1. 9. 3. 1.]]

reshape创建多维数组

b = np.arange(120).reshape(2,4,5,3)
print(b.shape) #(2,4,5,3)

a.resize()

同reshape(),返回一个修改后的数组,会更改原始数组
resize() 参数中不可以有负数

#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
# # a.resize(new_shape) 返回一个修改后的数组,会更改原始数组
a = np.array([[3.0, 9.0, 8.0, 0.0],[1.0, 4.0, 6.0, 5.0],[1.0, 9.0, 3.0, 1.0]])
print(a.shape) # (3,4)
a.resize(2,6)
print(a) # [[3. 9. 8. 0. 1. 4.] [6. 5. 1. 9. 3. 1.]]
a.resize(2,2,3)
print(a) # [[[3. 9. 8.] [0. 1. 4.]] [[6. 5. 1.] [9. 3. 1.]]]
a.resize(1,-1)
print(a) # ValueError: negative dimensions not allowed
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐