8

I have a matrix foo with n rows and m columns. Example:

>>> import numpy as np
>>> foo = np.arange(6).reshape(3, 2) # n=3 and m=2 in our example
>>> print(foo)
array([[0, 1],
       [2, 3],
       [4, 5]])

I have an array bar with n elements. Example:

>>> bar = np.array([9, 8, 7])

I have a list ind of length n that contains column indices. Example:

>>> ind = np.array([0, 0, 1], dtype='i')

I would like to use the column indices ind to assign the values of bar to the matrix foo. I would like to do this per row. Assume that the function that does this is called assign_function, my output would look as follows:

>>> assign_function(ind, bar, foo)
>>> print(foo)
array([[9, 1],
       [8, 3],
       [4, 7]])

Is there a pythonic way to do this?

2
  • 1
    foo[np.arange(len(foo)), ind] = bar? Commented Dec 19, 2017 at 16:28
  • To start with, the result you say to with to be getting is not corresponding to the variables defined, right? Commented Dec 19, 2017 at 16:31

2 Answers 2

7

Since ind takes care of the first axis, you just need the indexer for the zeroth axis. You can do this pretty simply with np.arange:

foo[np.arange(len(foo)), ind] = bar
foo

array([[9, 1],
       [8, 3],
       [4, 7]])
Sign up to request clarification or add additional context in comments.

Comments

3

Leveraging broadcasting alongwith masking -

foo[ind[:,None] == range(foo.shape[1])] = bar

Sample step-by-step run -

# Input array
In [118]: foo
Out[118]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

# Mask of places to be assigned
In [119]: ind[:,None] == range(foo.shape[1])
Out[119]: 
array([[ True, False],
       [ True, False],
       [False,  True]], dtype=bool)

# Assign values off bar
In [120]: foo[ind[:,None] == range(foo.shape[1])] = bar

# Verify
In [121]: foo
Out[121]: 
array([[9, 1],
       [8, 3],
       [4, 7]])

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.