NumPy Reshape Array Guide

In NumPy, you can use the reshape() function to change the shape of an array. The reshape() function takes a tuple as a parameter, which represents the new shape of the array.

Here is an example:

import numpy as np

# 创建一个1维数组
arr = np.array([1, 2, 3, 4, 5, 6])

# 将1维数组转换为2行3列的二维数组
new_arr = arr.reshape((2, 3))

print(new_arr)

The output result is:

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

The reshape() function can also take -1 as a parameter, which means it will automatically calculate the size of that dimension. For example, if you want to convert an array into a two-dimensional array with 3 rows, you can write it like this:

import numpy as np

# 创建一个1维数组
arr = np.array([1, 2, 3, 4, 5, 6])

# 将1维数组转换为有3行的二维数组
new_arr = arr.reshape((3, -1))

print(new_arr)

The output is:

[[1 2]
 [3 4]
 [5 6]]
bannerAds