The Python Oracle

np.where for 2d array, manipulate whole rows

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Question
00:43 Accepted answer (Score 2)
01:14 Answer 2 (Score 2)
01:28 Thank you

--

Full question
https://stackoverflow.com/questions/7158...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #numpy #arraybroadcasting

#avk47



ANSWER 1

Score 2


IIUC you want something like this:

condition = array[:,0]==1
new_array[condition,:] = array[condition,:3]
new_array[~condition,:] = array[~condition,-3:]



ACCEPTED ANSWER

Score 2


If you want to use np.where:

import numpy as np
array = np.array([
    [1, 2, 3, 4],
    [1, 2, 4, 2],
    [2, 3, 4, 6]
])

cond = array[:, 0] == 1
np.where(cond[:, None], array[:,:3], array[:,-3:])

output:

array([[1, 2, 3],
       [1, 2, 4],
       [3, 4, 6]])

EDIT

slightly more concise version:

np.where(array[:, [0]] == 1, array[:,:3], array[:,-3:])