1

Apologies is the title is not correct. I didn't know how to describe exactly what I am looking for. So coming from Matlab I want to be able to do the following in Python in one line if possible

Say I have an index array:

index_array= np.array([0,1,1,0,0,0,1])

and a data array: data_array = np.zeros([len(index_array),2])

I want to place a value (e.g. 100) where index_array=0 to the data_array[:,0] and where index_array=1 to data_array[:,1]

I matlab you could do it with one line. Something like data_array(index_array)=100

The best I could figure out in python is this

data_array [index_array==0,0]=100

data_array [index_array==1,1]=100

Is it possible to do it more efficiently (w.r.t. lines of code). Also it would be nice to scale for additional dimensions in data_array (beyond 2d)

1 Answer 1

1

If I understand your question correctly, please try this:

import numpy as np
index_array= np.array([0,1,1,0,0,0,1],dtype=bool)
data_array = np.zeros([len(index_array),2])
data_array[index_array,:]=100
print(data_array)

Here, index_array is instantiated as boolean. Or it can convert index_array to boolean using == (index_array==0).

Use data_array[index_array,...]=100 if there are additional dimensions.

------ CORRECTED VERSION ------

Hope I now understand your question. So try this:

import numpy as np
index_array= np.array([0,1,1,0,2,0,1,2])
data_array = np.zeros([len(index_array),3])

data_array[np.arange(len(index_array)), index_array] = 100

print(data_array)
Sign up to request clarification or add additional context in comments.

4 Comments

ok this works. I guess I omitted the boolean type thats why mine didnt work. However, I am not sure this naturally extends to more than 2 dimensions? Say, index_array= np.array([0,1,1,0,2,0,1,2],dtype=bool) and data_array = np.zeros([len(index_array),3]). Then using data_array[index_array,:]=100 produces the wrong result. Because when casting the index_array to boolean, anything nonzero becomes true.
Please read the end of my answer "Use data_array[index_array,...]=100 if there are additional dimensions."
I did. I used this data_array[index_array,...]= 100 verbatim but I got the same result as before. The problem comes from setting index_array= np.array([0,1,1,0,2,0,1,2],dtype=bool) because 1 and 2 are the same from the boolean point of view
Ok, I understand that's a slightly different question. See corrected version in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.