Numpy中reshape函数用于改变数组形状而不改变数据,新形状元素总数需匹配原数组,如一维12个元素可变为(3,4)或(2,2,3),但不能为(3,5);order参数控制读取顺序,默认'C'行优先;reshape通常返回视图以节省内存,当数据不连续或需重排时返回副本,可通过arr.base判断是否为视图,必要时可用.copy()强制复制。

Numpy中改变数组形状的核心方法就是
reshape
numpy.reshape(a, newshape, order='C')
a
newshape
(3, 4)
(2, 2, 3)
这里有个关键点,新形状的元素总数必须与原始数组的元素总数一致。如果你的原始数组有12个元素,你不能把它重塑成
(3, 5)
3 * 5 = 15
order
'C'
'F'
'C'
立即学习“Python免费学习笔记(深入)”;
import numpy as np
# 示例1:一维到二维
arr1d = np.arange(12)
print("原始一维数组:", arr1d)
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
arr2d = arr1d.reshape((3, 4))
print("\n重塑为(3, 4)的二维数组:\n", arr2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# 示例2:使用-1自动推断
arr_unknown_dim = np.arange(15)
arr_reshaped_auto = arr_unknown_dim.reshape((3, -1)) # -1 会自动计算为5
print("\n使用-1自动推断的数组形状:\n", arr_reshaped_auto)
# [[ 0 1 2 3 4]
# [ 5 6 7 8 9]
# [10 11 12 13 14]]
# 示例3:三维重塑
arr_original = np.arange(24).reshape((2, 3, 4))
print("\n原始三维数组:\n", arr_original)
# [[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
#
# [[12 13 14 15]
# [16 17 18 19]
# [20 21 22 23]]]
arr_new_shape = arr_original.reshape((4, 6))
print("\n重塑为(4, 6)的二维数组:\n", arr_new_shape)
# [[ 0 1 2 3 4 5]
# [ 6 7 8 9 10 11]
# [12 13 14 15 16 17]
# [18 19 20 21 22 23]]这是一个很常见的问题,也挺重要的,因为它直接关系到内存使用和数据修改的副作用。通常情况下,
reshape
但是,也有例外。如果原始数组的数据在内存中不是连续的(比如你对一个数组进行了转置
transpose
reshape
要判断一个
reshape
arr.base is None
arr.base is original_array
arr.base
None
import numpy as np
# 示例1:通常是视图
original_arr = np.arange(12)
reshaped_view = original_arr.reshape((3, 4))
print("原始数组:", original_arr)
print("重塑后的视图:\n", reshaped_view)
print("reshaped_view是original_arr的视图吗?", reshaped_view.base is original_arr) # True
# 修改视图会影响原始数组
reshaped_view[0, 0] = 99
print("修改视图后,原始数组:\n", original_arr) # [99 1 2 3 4 5 6 7 8 9 10 11]
# 示例2:何时会创建副本 (例如,需要改变内存布局)
# 假设我们有一个非C-contiguous的数组
arr_f_order = np.arange(12).reshape((3, 4), order='F')
print("\nF-order数组:\n", arr_f_order)
# 重塑成C-order的形状,从F-order到C-order的reshape,如果形状变化,通常会触发copy
reshaped_c_order = arr_f_order.reshape((4, 3), order='C')
print("reshaped_c_order是arr_f_order的视图吗?", reshaped_c_order.base is arr_f_order) # False
# 稳妥起见,如果你想强制创建一个副本,可以使用 .copy()
original_arr_for_copy = np.arange(12)
reshaped_copy = original_arr_for_copy.reshape((4, 3)).copy()
print("reshaped_copy是original_arr_for_copy的视图吗?", reshaped_copy.base is original_arr_for_copy) # False我个人在实践中,如果我不确定是视图还是副本,或者我明确不希望修改原始数据,我都会习惯性地在
reshape
.copy()
以上就是python numpy如何改变数组的形状_numpy reshape函数改变数组形状的方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号