A R.
A R.

Reputation: 333

Slicing numpy array taking every nth element

I have an numpy array of shape 24576x25 and i want to extract 3 array out of it. Where the first array contains the every 1st,4th,7th,10th,... element while second array contains 2nd,5,8,11th,... element and third array with 3rd,6,9,12th,... The output array sizes would be 8192x25. I was doing the following in MATLAB

c = reshape(a,1,[]);
x = c(:,1:3:end);
y = c(:,2:3:end);
z = c(:,3:3:end);

I have tried a[:,0::3] in python but this works only if i have array of shape divisible by 3. What can i do?

X,Y = np.mgrid[0:24576:1, 0:25:1]
a = X[:,::,3]
b = X[:,1::3]
c = X[:,2::3]

does not work either. I need a,b,c.shape = 8192x25

Upvotes: 1

Views: 6142

Answers (2)

JaHoff
JaHoff

Reputation: 206

A simple tweak to your original attempt should yield the results you want:

X,Y = np.mgrid[0:24576:1, 0:25:1]
a = X[0::3,:]
b = X[1::3,:]
c = X[2::3,:]

Upvotes: 2

bigbounty
bigbounty

Reputation: 17358

import numpy as np
a = np.arange(24576*25).reshape((24576,25))
a[::3]

a[::3].shape gives you (8192, 25)

Upvotes: 0

Related Questions