numpy的屏蔽之后不改变的数组元素的值 [英] Numpy doesn't change value of an array element after masking

查看:208
本文介绍了numpy的屏蔽之后不改变的数组元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个怪异的行为试图改变今天numpy的数组元素的价值,我想了解为什么它没有工作。我有两个阵列( A B ),我想改变b,其中a> 0时的值。

I had a weird behaviour trying to change the value of an element of a numpy array today, and I would like to understand why it didn't work. I have two arrays (a and b), and I want to change the values of b where a > 0.

a = array([[ 1.,  0.,  0.],
           [ 0.,  1.,  0.],
           [ 0.,  0.,  1.]])

b = array([[ 5.,  0.,  0.],
           [ 0.,  5.,  0.],
           [ 0.,  0.,  5.]])

mask = a > 0

print b[mask][0]
   => 5.0

b[mask][0] = 10

print b[mask][0]
   => 5.0

可能有人请解释为什么分配B〔面膜] [0]并没有改变我的价值5.0?

Could someone please explain why the assignment b[mask][0] didn't change my value 5.0?

推荐答案

B [面具] 的复制B] B [面膜] [0] = 1 是有效的:

 c = b[mask]
 c[0] = 1

C 中的数据元素不是(一般)元素的连续块b

 b[mask] = 10
 b[mask] = [10, 11, 12]

您可以将值分配给 B [面具] 时,它是在左边的唯一的事。您需要更改所有的蒙面元素。

You can assign values to b[mask] when it is the only thing on the left. You need to change all the masked elements.

如果您需要更改一个或两个,那么首先改变了掩盖,因此只选择那些元素。

If you need to change one or two, then first change the mask so it selects only those elements.

在一般

 b[...][...] = ...

是不是好的做法。有时候,它的工作原理(如果第一个索引是产生视图 A片),但你不应该指望它。它需要一段时间才能充分掌握视图和副本之间的差异。

is not good practice. Sometimes it works (if the first indexing is a slice that produces a view), but you shouldn't count on it. It takes a while to full grasp the difference between a view and copy.

[] 获得由Python间preTER到调用转换为 __的GetItem __ __ setitem __ 。下面对是等价的:

The [] get translated by the Python interpreter into calls to __getitem__ or __setitem__. The following pairs are equivalent:

 c = b[mask]
 c = b.__getitem__(mask)

 b[mask] = 10
 b.__setitem__(mask, 10)

 b[mask][0] = 10
 b.__getitem__(mask).__setitem__(0, 10)

B [面膜] [10] 2的操作,一大家子后面一组。该组的get结果进行操作。它修改 B 只有GET的结果是一个视图。

b[mask][10] is 2 operations, a get followed by a set. The set operates on the result of the get. It modifies b only if the result of the get is a view.

这篇关于numpy的屏蔽之后不改变的数组元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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