Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simultaneously select all odd rows and all even columns of an array

Tags:

python

numpy

I'm new to programming and I need a program, that can select all odd rows and all even columns of a Numpy array at the same time in one code. here is what I tried:

>In [78]: a  >Out[78]: >array([[ 1,  2,  3,  4,  5], >       [ 6,  7,  8,  9, 10], >       [11, 12, 13, 14, 15], >       [16, 17, 18, 19, 20]]) > >In [79]: for value in range(a.shape[0]): >     if value %2 == 0: >        print a[value,:]  >[1 2 3 4 5] >[11 12 13 14 15] > >In [82]: for value in range(a.shape[1]): >    if value %2 == 1: >        print a[:,value]  >[ 2  7 12 17] >[ 4  9 14 19] 

I've read something with (: even) but don't know in which way I could use it. Thanks for your Help.

Han

like image 968
user1339701 Avatar asked Apr 17 '12 20:04

user1339701


People also ask

How do you select odd columns in R?

The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector.

How do you extract an odd number from an array in Python?

This Python Program uses the for loop range to Print the Odd Numbers in a Numpy Array. The if statement (if (oddArr[i] % 2 != 0)) checks the numpy array item at each index position is not divisible by two. If True, (print(oddArr[i], end = ” “)) print that numpy Odd array number.

How do you select a row from an array in Python?

We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.


2 Answers

Let's say you have this array, x:

>>> import numpy >>> x = numpy.array([[ 1,  2,  3,  4,  5], ... [ 6,  7,  8,  9, 10], ... [11, 12, 13, 14, 15], ... [16, 17, 18, 19, 20]]) 

To get every other odd row, like you mentioned above:

>>> x[::2] array([[ 1,  2,  3,  4,  5],        [11, 12, 13, 14, 15]]) 

To get every other even column, like you mentioned above:

>>> x[:, 1::2] array([[ 2,  4],        [ 7,  9],        [12, 14],        [17, 19]]) 

Then, combining them together yields:

>>> x[::2, 1::2] array([[ 2,  4],        [12, 14]]) 

For more details, see the Indexing docs page.

like image 74
jterrace Avatar answered Sep 18 '22 11:09

jterrace


To get every other odd column:

 x[:,0::2] 
like image 29
Taehee Jeong Avatar answered Sep 18 '22 11:09

Taehee Jeong