How to truncate a numpy array?

1arnav1 picture 1arnav1 · Jun 18, 2018 · Viewed 13k times · Source

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?

Answer

kmario23 picture kmario23 · Jun 18, 2018

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)