简体   繁体   English

将 numpy 数组行列值设置为另一个数组的列值

[英]Set numpy array rows column values to column values of another array

I am trying to select rows with values in their first two columns matching with those of another array and set their last columns values to the last column values of that array.我正在尝试 select 行的前两列中的值与另一个数组的值匹配,并将它们的最后一列值设置为该数组的最后一列值。

I've specifically tried to do something like this:我特别尝试做这样的事情:

import numpy as np

array_1 = np.zeros((10,3), order = "F", dtype = int)

array_2 = np.zeros((5,3), order = "F", dtype = int)

array_1[:5][:,0] = 1
array_1[:5][:,1] = 1

array_2[:,0] = 1
array_2[:,1] = 1
array_2[:,2] = 3

array_1[:,2][np.where((array_1[:,0] == array_2[:,0]) & (array_1[:,1] == array_2[:,1]))] = array_2[:,2]

The objective is to set the value of column 2 of rows matching to 3. (same as array_2)目标是将匹配行的第 2 列的值设置为 3。(与 array_2 相同)

I've also tried to do the same thing with masking.我也尝试用遮罩做同样的事情。

It always complaints about a shape mismatch, so I assume I am doing something wrong since the objective is only to change the value of one particular column, for those row matches.它总是抱怨形状不匹配,所以我认为我做错了什么,因为目标只是为了那些行匹配更改一个特定列的值。

What is the way to do this?这样做的方法是什么?

I was able to solve it like this:我能够像这样解决它:

import numpy as np

array_1 = np.zeros((10,3), order = "F", dtype = int)

array_2 = np.zeros((5,3), order = "F", dtype = int)

array_1[:5][:,0] = 1
array_1[:5][:,1] = 1

array_2[:,0] = 1
array_2[:,1] = 1
array_2[:,2] = 3

m = (array_1[:,:2][:,None] == array_2[:,:2]).all(-1).any(1)

array_1[:,2][m] = array_2[:,2]

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

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