codeprb
codeprb

Reputation: 27

Selecting odd numbers of rows and columns

HI I have this Matlab code which is picking the odd number of rows and columns from Residuals Matrix. I would like to convert this piece of code from to Python. Could you please let me know if my code is correct.

Matlab code:

NewRes(:,:,Channel,:) = Residuals([1:2:size(Residuals,1)],[1:2:size(Residuals,1)],Channel,:);

Python code:

NewRes[:, :, Channel, :] = Residuals(Residuals[::2], Residuals[::2], Channel, :)

Does my code represent the even number of rows and columns? How can be size(Residuals,1) can be considered.

example output from matlab code

Residuals =

     1     2     3     4
     3     4     5     6
     8     9     3     1

>>  Residuals([1:2:size(Residuals,1)],[1:2:size(Residuals,1)], :, :);
>> Residuals

Residuals =

     1     2     3     4
     3     4     5     6
     8     9     3     1

>> Newres = Residuals([1:2:size(Residuals,1)],[1:2:size(Residuals,1)], :, :);
>> Newres

Newres =

     1     3
     8     3

Upvotes: 0

Views: 2933

Answers (2)

BENY
BENY

Reputation: 323316

You can do with .iloc with %

df.iloc[np.arange(df.shape[0]) % 2 == 0, np.arange(df.shape[1]) % 2 == 0]
   1  3
0  1  3
2  8  3

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

iloc is certainly the way to go:

df.iloc[::2, ::2]

Upvotes: 2

Related Questions