Search code examples
pythonnumpyreshapevalueerrornumpy-slicing

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?


Solution

  • 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)