如何截断一个numpy数组?

问题描述 投票:1回答:2

我试图用以下代码行截断“数据”(大小为112943)来形成(1,15000):

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

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

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

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

python numpy reshape valueerror numpy-slicing
2个回答
4
投票

换句话说,由于您只需要前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)

2
投票

你可以使用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作为危险的就地版本。在脚本或模块中,您不必,也不应该。

© www.soinside.com 2019 - 2024. All rights reserved.