简体   繁体   English

将值分配给 Numpy 数组中的不同索引位置

[英]Assign values to different index positions in Numpy array

Say I have an array说我有一个数组

np.zeros((4,2))

I have a list of values [4,3,2,1] , which I want to assign to the following positions: [(0,0),(1,1),(2,1),(3,0)]我有一个值列表[4,3,2,1] ,我想将其分配给以下位置: [(0,0),(1,1),(2,1),(3,0)]

How can I do that without using the for loop or flattening the array?如何在不使用 for 循环或展平数组的情况下做到这一点?

I can use fancy index to retrieve the value, but not to assign them.我可以使用花哨的索引来检索值,但不能分配它们。

======Update========= ======更新========

Thanks to @hpaulj, I realize the bug in my original code is.感谢@hpaulj,我意识到我的原始代码中的错误是。

When I use zeros_like to initiate the array, it defaults to int and truncates values.当我使用zeros_like启动数组时,它默认为int并截断值。 Therefore, it looks like I did not assign anything!因此,看起来我没有分配任何东西!

You can use tuple indexing:您可以使用元组索引:

>>> import numpy as np
>>> a = np.zeros((4,2))
>>> vals = [4,3,2,1]
>>> pos = [(0,0),(1,1),(2,0),(3,1)]
>>> rows, cols = zip(*pos)
>>> a[rows, cols] = vals
>>> a
array([[ 4.,  0.],
       [ 0.,  3.],
       [ 2.,  0.],
       [ 0.,  1.]])

Here is a streamlined version of @wim's answer based on @hpaulj's comment.这是基于@hpaulj 评论的@wim 答案的简化版本。 np.transpose automatically converts the Python list of tuples into a NumPy array and transposes it. np.transpose自动将 Python 元组列表转换为 NumPy 数组并对其进行转置。 tuple casts the index coordinates to tuples which works because a[rows, cols] is equivalent to a[(rows, cols)] in NumPy. tuple将索引坐标转换为 tuples,这是因为a[rows, cols]等价于 NumPy 中的a[(rows, cols)]

import numpy as np
a = np.zeros((4, 2))
vals = range(4)
indices = [(0, 0), (1, 1), (2, 0), (3, 1)]
a[tuple(np.transpose(indices))] = vals
print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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