温馨提示×

numpy怎么将二维数组转为一维数组

小亿
131
2023-11-29 19:26:52
栏目: 编程语言

在NumPy中,可以使用flatten()方法将二维数组转换为一维数组。

下面是一个示例:

import numpy as np

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

# 将二维数组转为一维数组
arr_1d = arr_2d.flatten()

print(arr_1d)

输出结果:

[1 2 3 4 5 6]

另外,还可以使用reshape()方法将二维数组转换为一维数组。

下面是使用reshape()方法的示例:

import numpy as np

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

# 使用reshape方法将二维数组转为一维数组
arr_1d = arr_2d.reshape(-1)

print(arr_1d)

输出结果与前面的示例相同:

[1 2 3 4 5 6]

0