将值分配给Numpy数组中的不同索引位置 [英] Assign values to different index positions in Numpy array

查看:185
本文介绍了将值分配给Numpy数组中的不同索引位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组

np.zeros((4,2))

np.zeros((4,2))

我有一个值[4,3,2,1]的列表,我想将它们分配给以下位置: [(0,0),(1,1),(2,1),(3,0)]

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)]

如何在不使用for循环或展平数组的情况下做到这一点?

How can I do that without using the for loop or flattening the array?

我可以使用花哨的索引来检索值,但不能给它们赋值.

I can use fancy index to retrieve the value, but not to assign them.

======更新========

======Update=========

感谢@hpaulj,我意识到原始代码中的错误是

Thanks to @hpaulj, I realize the bug in my original code is.

当我使用zeros_like初始化数组时,它默认为int并截断值.因此,看来我没有分配任何东西!

When I use zeros_like to initiate the array, it defaults to int and truncates values. Therefore, it looks like I did not assign anything!

推荐答案

您可以使用元组索引:

>>> 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.]])

这篇关于将值分配给Numpy数组中的不同索引位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆