改变一个NumPy数组的尺寸
让我们讨论一下如何改变一个数组的尺寸。在NumPy中,这可以通过多种方式实现。让我们来讨论一下每一种方法。
方法#1:使用Shape()
语法 :
array_name.shape()
# importing numpy
import numpy as np
def main():
# initialising array
print('Initialised array')
gfg = np.array([1, 2, 3, 4])
print(gfg)
# checking current shape
print('current shape of the array')
print(gfg.shape)
# modifying array according to new dimensions
print('changing shape to 2,3')
gfg.shape = (2, 2)
print(gfg)
if __name__ == "__main__":
main()
输出:
Initialised array
[1 2 3 4]
current shape of the array
(4,)
changing shape to 2,3
[[1 2]
[3 4]]
方法二:使用 reshape()。
reshape()函数的顺序参数是高级的,是可选的。当我们使用C和F时,输出是不同的,因为NumPy改变结果数组的索引的方式不同。顺序A使NumPy根据内存块的可用大小,从C或F中选择最佳的顺序。
C级和F级之间的区别
语法 :
numpy.reshape(array_name, newshape, order= 'C' or 'F' or 'A')
# importing numpy
import numpy as np
def main():
# initialising array
gfg = np.arange(1, 10)
print('initialised array')
print(gfg)
# reshaping array into a 3x3 with order C
print('3x3 order C array')
print(np.reshape(gfg, (3, 3), order='C'))
# reshaping array into a 3x3 with order F
print('3x3 order F array')
print(np.reshape(gfg, (3, 3), order='F'))
# reshaping array into a 3x3 with order A
print('3x3 order A array')
print(np.reshape(gfg, (3, 3), order='A'))
if __name__ == "__main__":
main()
输出 :
initialised array
[1 2 3 4 5 6 7 8 9]
3x3 order C array
[[1 2 3]
[4 5 6]
[7 8 9]]
3x3 order F array
[[1 4 7]
[2 5 8]
[3 6 9]]
3x3 order A array
[[1 2 3]
[4 5 6]
[7 8 9]]
方法#3:使用 resize()
数组的形状也可以用resize()方法来改变。如果指定的尺寸大于实际的数组,那么新数组中多余的空间将被原数组的重复拷贝所填充。
语法 :
numpy.resize(a, new_shape)
# importing numpy
import numpy as np
def main():
# initialise array
gfg = np.arange(1, 10)
print('initialised array')
print(gfg)
# resezed array with dimensions in
# range of original array
np.resize(gfg, (3, 3))
print('3x3 array')
print(gfg)
# re array with dimensions larger than
# original array
np.resize(gfg, (4, 4))
# extra spaces will be filled with repeated
# copies of original array
print('4x4 array')
print(gfg)
# resize array with dimensions larger than
# original array
gfg.resize(5, 5)
# extra spaces will be filled with zeros
print('5x5 array')
print(gfg)
if __name__ == "__main__":
main()
输出 :
initialised array
[1 2 3 4 5 6 7 8 9]
3x3 array
[1 2 3 4 5 6 7 8 9]
4x4 array
[1 2 3 4 5 6 7 8 9]
5x5 array
[[1 2 3 4 5]
[6 7 8 9 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]