python - 根据不同二维数组的条件更新 numpy 二维数组

标签 python numpy matrix multidimensional-array

在我正在编写的代码中,我有三个具有相同维度 (m x n) 的 2D numpy 数组,每个 2D 数组包含有关特定特征的信息,但每个对应的单元格(具有特定的行/列值)所有三个二维数组都对应于一个特定的人。三个二维数组是trait1、trait2 和trait3。例如,如果在位置 (0,0) 处只有特征 1 和特征 2 的值为 1,但特征 3 没有,则人员 (0, 0) 将具有特征 1、2,但不是三个。

根据同一位置相同维度的其他相应二维数组的值更新特定位置处的二维数组的有效方法是什么?也就是说,我如何有效地更新更新特定位置处的二维数组,以便同一位置处的其他二维数组满足特定条件?

我目前正在尝试根据trait1和trait2的当前值来更新2D数组trait1和trait2的值(使得对应的trait1值== 1,对应的trait2值== 0);我还尝试根据 Trait1 和 Trait2 的当前值(在与之前相同的条件下)更新 Trait3 的值。但是,如果不使用嵌套 for 循环,我会遇到麻烦,这会大大减慢我的程序速度。

下面是我目前的方法,它有效,但对于我的目的来说太慢了:

for i in range (0, m):
        for j in range (0, n):
            if trait1[i][j] == 1:
                if trait2[i][j] == 0:
                    trait1[i][j] = 0
                    trait2[i][j] = 1
                    new_color(i, j, 1) #updates the color of the specific person on a grid
                    trait3[i][j] = 0 

            elif trait1[i][j] == 0:
                if trait2[i][j] <= 0:
                    trait1[i][j] = 1
                    trait2[i][j] = 0
                    new_color(i, j, 0)

最佳答案

如果你确实使用循环,Numpy 数组真的很慢。如果你可以使用矩阵运算/numpy 函数来处理所有事情,它会快得多。 在您的情况下,您可以首先提取您感兴趣的索引,然后像这样更新矩阵:

import numpy as np

np.random.seed(1)
# Generate some sample data
trait1, trait2, trait3 = ( np.random.randint(0,2, [4,4]) for _ in range(3) )
In [4]: trait1
Out[4]:
array([[1, 1, 0, 0],
       [1, 1, 1, 1],
       [1, 0, 0, 1],
       [0, 1, 1, 0]])
In [5]: trait2
Out[5]:
array([[0, 1, 0, 0],
       [0, 1, 0, 0],
       [1, 0, 0, 0],
       [1, 0, 0, 0]])
In [6]: trait3
Out[6]:
array([[1, 1, 1, 1],
       [1, 0, 0, 0],
       [1, 1, 1, 1],
       [1, 1, 0, 1]])

然后:

cond1_idx = np.where((trait1 == 1) & (trait2==0))
cond2_idx = np.where((trait1 == 0) & (trait2<=0))

trait1[cond1_idx] = 0
trait2[cond1_idx] = 1
trait3[cond1_idx] = 0
[ new_color(i, j, 1) for i,j in zip(*cond1_idx) ]

trait1[cond2_idx] = 1
trait2[cond2_idx] = 0
[ new_color(i, j, 0) for i,j in zip(*cond2_idx) ]

结果:

In [2]: trait1
Out[2]:
array([[0, 1, 1, 1],
       [0, 1, 0, 0],
       [1, 1, 1, 0],
       [0, 0, 0, 1]])

In [3]: trait2
Out[3]:
array([[1, 1, 0, 0],
       [1, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 0]])

In [4]: trait3
Out[4]:
array([[0, 1, 1, 1],
       [0, 0, 0, 0],
       [1, 1, 1, 0],
       [1, 0, 0, 1]])

我无法真正测试new_color,因为我没有该功能

关于python - 根据不同二维数组的条件更新 numpy 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57382732/

相关文章:

python - MySQL, python 更新行如果为空

python - 索引错误: invalid index

python - 拼接 NumPy 数组

matlab - 如何将矩阵中强元素附近的弱元素归零?

matlab - 根据matlab中的一列对整个矩阵进行排序

java - 在 Java 中旋转 NxN 矩阵

python - 我如何在整个文本文件中搜索一行文本

python - Pytorch:除了一个求和之外的所有求和?

python - 如何将numpy数组转换为元组

PythonAnywhere->ImportError 引发加载 nrpccms.newsroom.templatetags.blog_extras : No module named settings