[英]Assign values to a numpy array for each row with specified columns
I have a matrix foo
with n
rows and m
columns. 我有一个矩阵foo
有n
行和m
列。 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. 我有一个包含n
元素的数组bar
。 Example: 例:
>>> bar = np.array([9, 8, 7])
I have a list ind
of length n
that contains column indices. 我有一个长度为n
的列表ind
,其中包含列索引。 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
. 我想使用列索引ind
将bar
的值赋给矩阵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
,我的输出将如下所示:
>>> assign_function(ind, bar, foo)
>>> print(foo)
array([[9, 1],
[8, 3],
[4, 7]])
Is there a pythonic way to do this? 有没有pythonic方式来做到这一点?
Since ind
takes care of the first axis, you just need the indexer for the zeroth axis. 由于ind
负责第一个轴,你只需要第0个轴的索引器。 You can do this pretty simply with np.arange
: 你可以用np.arange
简单地做到这np.arange
:
foo[np.arange(len(foo)), ind] = bar
foo
array([[9, 1],
[8, 3],
[4, 7]])
Leveraging broadcasting
alongwith masking
- 利用broadcasting
和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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.