numpy索引过滤更改多个变量

时间:2019-06-04 13:37:45

标签: python-3.x numpy variable-assignment matrix-indexing

将索引过滤应用于numpy数组(b[b < 3] = 0)时,我注意到意外的结果。从或向要过滤的变量分配的任何变量都将应用相同的过滤器,即,如果b = aa将被过滤为与b相同的过滤器。

我创建了一个测试文件,以查看将索引过滤应用于变量时哪些变量会受到影响。我已经在下面的代码中运行了结果,给出了我期望得到的结果。

import numpy as np

class tester1(object):
    def __init__(self):
        self.a = np.array([[1, 2, 3], [4, 5, 6]])
        self.b = []
        self.c = []
        self.d = []

    def test1(self):
        self.b = self.a
        self.c = self.b
        self.d = self.c
        d = self.d
        e = d
        d[d < 3] = 0
        print('self.a')
        print(self.a)
        print('self.b')
        print(self.b)
        print('self.c')
        print(self.c)
        print('d')
        print(d)
        print('e')
        print(e)


class tester2(object):
    def __init__(self):
        self.d = np.array([[1, 2, 3], [4, 5, 6]])
        self.e = []
        self.t = tester1()
        self.t.test1()

    def test2(self):
        self.t.b = self.d
        self.t.c = self.t.b
        self.e = self.t.b
        self.t.b[self.t.b < 3] = 0
        print('self.t.b')
        print(self.t.b)
        print('self.t.c')
        print(self.t.c)
        print('self.d')
        print(self.d)
        print('self.e')
        print(self.e)

    def test3(self):
        print('self.d')
        print(self.d)
        self.e = self.d
        a = np.array([[False, False, False], [False, True, True]])
        f = self.d
        f[a] = 0
        print('self.d')
        print(self.d)
        print('self.e')
        print(self.e)
        print('f')
        print(f)

    def test4(self):
        a = self.t.a
        b = a
        c = b
        c[c > 4] = 2
        print('self.t.a')
        print(self.t.a)
        print('b')
        print(b)
        print('c')
        print(c)

该类的结果在顶部,而我期望的结果在底部。

当我运行t = tester2()

self.a  [[0 0 3] [4 5 6]]  # Actual
self.a  [[1 2 3] [4 5 6]]  # Expected


self.b  [[0 0 3] [4 5 6]]
self.b  [[1 2 3] [4 5 6]]

self.c  [[0 0 3] [4 5 6]]
self.c  [[1 2 3] [4 5 6]]

d   [[0 0 3] [4 5 6]]
d   [[0 0 3] [4 5 6]]

e   [[0 0 3] [4 5 6]]
e   [[1 2 3] [4 5 6]]

我运行t.test2()

self.t.b [[0 0 3] [4 5 6]]  # Actual
self.t.b [[0 0 3] [4 5 6]]  # Expected

self.t.c [[0 0 3] [4 5 6]]
self.t.c [[1 2 3] [4 5 6]]

self.d   [[0 0 3] [4 5 6]]
self.d   [[1 2 3] [4 5 6]]

self.e   [[0 0 3] [4 5 6]]
self.e   [[1 2 3] [4 5 6]]

我运行t.test3()

self.d  [[0 0 3] [4 5 6]]  # Actual
self.d  [[1 2 3] [4 5 6]]  # Expected

self.d  [[0 0 3] [4 0 0]]
self.d  [[1 2 3] [4 5 6]]

self.e  [[0 0 3] [4 0 0]]
self.e  [[1 2 3] [4 5 6]]

f   [[0 0 3] [4 0 0]]
f   [[1 2 3] [4 0 0]]

我运行t.test4()

self.t.a [[0 0 3] [4 2 2]]  # Actual
self.t.a [[1 2 3] [4 5 6]]  # Expected

b    [[0 0 3] [4 2 2]]
b    [[1 2 3] [4 5 6]]

c    [[0 0 3] [4 2 2]]
c    [[1 2 3] [4 2 2]]

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为您将变量a,b,c和d分配给了同一数组。将变量视为对该数组的访问。如果将过滤应用于此数组。然后它将影响所有变量,因为它们都指向同一数组。如果要基于该数组分隔数组,可以使用复制方法,例如arr_b = arr_a.copy()或arr_b = arr_a [:]。