简体   繁体   English

为具有指定列的每一行的numpy数组赋值

[英]Assign values to a numpy array for each row with specified columns

I have a matrix foo with n rows and m columns. 我有一个矩阵foon行和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 . 我想使用列索引indbar的值赋给矩阵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 - 利用broadcastingmasking -

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM