Reputation: 1686
Let's say I have a 3D matrix I want to reduce. I would like to reduce the first dimension only to around 10 elements (it is best if it is 10 but not necessary). I used this code for that:
import numpy
m = numpy.random.rand(37,2,100)
new_m = m[0:-1:int(m.shape[0]/10)]
# new_m.shape = (12, 2, 100)
My problem is the following: I want the first and last elements of this first dimension to be the same than my original matrix. But with my current code, this condition does not hold for the last element:
new_m[0,:,:2], new_m[-1,:,:2]
#[[ 0.06081972 0.91343839] [ 0.89614534 0.33846807]]
#[[ 0.37289341 0.62491196] [ 0.30603305 0.1442681 ]]
m[0,:,:2], m[-1,:,:2]
#[[ 0.06081972 0.91343839] [ 0.89614534 0.33846807]]
#[[ 0.28143018 0.10626664] [ 0.30334235 0.29616713]]
As you can see new_m[-1]
is not equal to m[-1]
, and I would like them to be.
My tries/ideas:
m[-1]
to new_m
however I got this error:
AttributeError: 'numpy.ndarray' object has no attribute 'append'
new_m[-1] = m[-1]
, but I would like the space between the steps to be proportional (i.e. steps well separated).Any ideas, suggestions?
Upvotes: 2
Views: 82
Reputation: 8829
Since you're using numpy, you can exploit fancy indexing. We'll also use linespace
, which generates evenly spaced points in a range, including endpoints. The arguments are similar to what you'd pass to range
or your indexing method.
indexes = np.linspace(0, len(m) - 1, 10, dtype=int)
new_m = m[indexes]
Upvotes: 2