7

I am trying to truncate 'data' (which is size 112943) to shape (1,15000) with the following line of code:

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

However, that gives me the following error:

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

Any suggestions on how to fix this error?

kmario23
  • 57,311
  • 13
  • 161
  • 150
1arnav1
  • 187
  • 2
  • 3
  • 9
  • 1
    what is shape(data)? – skrubber Jun 18 '18 at 20:01
  • Truncate and reshape are two different operations. Truncate changes the size, but keeps the shape. Reshape keeps the size, but changes the shape. I suggest you use slicing. – DYZ Jun 18 '18 at 20:02
  • I'm trying to remove everything besides the first 15,000 elements – 1arnav1 Jun 18 '18 at 20:04
  • When you say "truncate", are you just looking to get a new array of the first 15,000 elements, possibly sharing the same memory, or to actually truncate the storage (or copy part of it) so the extra 800K or so of memory can be released? – abarnert Jun 18 '18 at 20:11

2 Answers2

12

In other words, since you want only the first 15K elements, you can use basic slicing for this:

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)
kmario23
  • 57,311
  • 13
  • 161
  • 150
4

You can use 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]])

Note that - I presume because the interactive shell keeps some extra references to recently evaluated things - I had to use refcheck=False for the in-place version which is dangerous. In a script or module you wouldn't have to and you shouldn't.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99