2

I have a function which gives me the index for a given value. Eg,

def F(value):
   index = do_something(value)
   return index

I want to use this index to fill a huge numpy array by 1s. Lets call array features

l = [1,4,2,3,7,5,3,6,.....]

NOTE: features.shape[0] = len(l)

for i in range(features.shape[0]):
    idx = F(l[i])
    features[i, idx] = 1

Is there a pythonic way to perform this (as the loop takes a lot of time if the array is huge)?

2 Answers 2

2

If you can vectorize F(value) you could write something like

indices = np.arange(features.shape[0])
feature_indices = F(l)

features.flat[indices, feature_indices] = 1
Sign up to request clarification or add additional context in comments.

1 Comment

F(value) is not vectorized
1

try this:

i = np.arange(features.shape[0]) # rows
j = np.vectorize(F)(np.array(l)) # columns
features[i,j] = 1

Comments

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.