创建numpy ndarray时触发‘buffer is too small’错误,但缓冲区大小匹配
np.ndarray创建数组时报错TypeError: buffer is too small for requested array的原因及解决办法
尝试创建一个简单的一维numpy ndarray时出现错误:
>>> np.ndarray(shape=(3,), buffer=np.array([1,2,3])) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: buffer is too small for requested array明明shape与传入的buffer相匹配,为何会出现该错误?
错误原因
np.ndarray的buffer参数要求传入原始字节缓冲区(比如bytes、bytearray或缓冲区对象),而非numpy数组对象本身。当你直接传入np.array([1,2,3])时,numpy会尝试从该数组对象的内存空间读取数据,而不是数组实际存储元素的内存区域——数组对象本身的内存远小于存储3个整数所需的字节数,因此会触发“buffer太小”的错误。
解决办法
方法1:使用np.array()直接创建(推荐)
这是numpy创建数组的标准方式,无需手动处理buffer:
import numpy as np arr = np.array([1,2,3])
方法2:正确使用np.ndarray的buffer参数
如果必须使用np.ndarray,需要传入数组的原始字节数据,并指定对应的dtype:
import numpy as np source_arr = np.array([1,2,3]) # 方式一:转为字节数据 new_arr = np.ndarray(shape=(3,), buffer=source_arr.tobytes(), dtype=source_arr.dtype) # 方式二:使用数组的缓冲区对象 new_arr = np.ndarray(shape=(3,), buffer=source_arr.data, dtype=source_arr.dtype)
内容的提问来源于stack exchange,提问作者OfirD
相关产品推荐
相关产品推荐

