Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a numpy array?

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?

like image 295
1arnav1 Avatar asked Jun 18 '18 19:06

1arnav1


2 Answers

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)
like image 108
kmario23 Avatar answered Oct 11 '22 01:10

kmario23


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.

like image 24
Paul Panzer Avatar answered Oct 11 '22 03:10

Paul Panzer