6

我正在尝试使用以下代码行将“数据”(大小为 112943)截断为形状(1,15000):

data = np.reshape(data, (1, 15000))

但是,这给了我以下错误:

ValueError: cannot reshape array of size 112943 into shape (1,15000)

有关如何解决此错误的任何建议?

4

2 回答 2

11

换句话说,由于您只需要前 15K 元素,您可以为此使用基本切片:

In [114]: arr = np.random.randn(112943)

In [115]: truncated_arr = arr[:15000]

In [116]: truncated_arr.shape
Out[116]: (15000,)

In [117]: truncated_arr = truncated_arr[None, :]

In [118]: truncated_arr.shape
Out[118]: (1, 15000)
于 2018-06-18T20:06:47.323 回答
4

您可以使用resize

>>> import numpy as np
>>> 
>>> a = np.arange(17)
>>> 
# copy
>>> np.resize(a, (3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> 
# in-place - only use if you know what you are doing
>>> a.resize((3, 3), refcheck=False)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

请注意 - 我认为是因为交互式 shell 保留了一些对最近评估的东西的额外引用 - 我不得不使用refcheck=False危险的就地版本。在脚本或模块中,您不必也不应该这样做。

于 2018-06-18T20:12:01.333 回答