How to reshape a dataset that's not aligned and throw away leftover data with numpy?

Viewed 173

I have an array with a random length of which I don't know the size of.

I want to reshape the array into a 2d array with a size of 128

np.reshape(array, (128, -1))

If I do this, there will be values that are leftover or more than needed, thus the function fails. How do I tell numpy to throw away leftover data or to throw away the data in hand if there isn't enough data to reshape?

1 Answers

You can just calculate how much data you have to throw away before (and slice it).

An example:

import numpy as np

data = np.array(np.random.rand(200))
# Setup target dimension
dim = 128
# Calculate the maximum index
max_index = (len(data)//dim)*dim
# Get valid data
data = data[:max_index]
# Reshape data to new dimension
new = np.reshape(data, (dim, -1))
Related