首页 > 解决方案 > 索引numpy两个数组

问题描述

我有两个数组。我想用其中一个作为第二个的参考,我该怎么做?我有以下数组A:

A = np.array([[1.00, 0.0, 1.03, 1.18],
          [0.0, 1.58, 0.0, 7.59],
          [1.00, 1.22, 1.07, 1.03]])

另外,我有数组 B:

B = np.array([[1.00, 2.00, 27.00, 10.00],
          [3.00, 9.00, 6.00, 2.00],
          [2.00, 6.00, 4.00, 15.00]])

我需要按[i,j]列识别 A 中所有零的位置/位置( ) 在同一个[i,j]。我不知道如何使用数组。

到目前为止我所做的:我可以解决这个问题,构建一个新数组 (C),其中包含来自 A 和 B 的 i 列(被视为数据框),然后删除第一列为零的行并执行操作(在循环序列)。我知道这不是最有效的方法。我也尝试将数组更改为数据框(然后应用loc),但我更喜欢使用数组进行数据操作。最后,我尝试了这个,但弹出以下消息arrays used as indices must be of integer (or boolean) type

我想学习一种新的方法来完成我的任务。非常感谢。

标签: arrayspython-3.xnumpyindexing

解决方案


解决方案:使用掩码数组

考虑到 and 的形式,A进行B所需计算的最简单方法是通过掩码数组。首先,您使用来自 的数据创建一个新的掩码数组,并B在其中的所有位置进行掩码A==0

marr = np.ma.masked_array(B, A==0)
print(f'the masked array looks like\n{marr}\n')

输出:

the masked array looks like
[[1.0 -- 27.0 10.0]
 [-- 9.0 -- 2.0]
 [2.0 6.0 4.0 15.0]]

一次对掩码数组中的所有列进行操作,无需循环

然后,您可以一次对所有被屏蔽的列执行各种操作(summeancumprod等),如下所示:

colsums = marr.sum(axis=0)
colmeans = marr.mean(axis=0)

print(f'sum of each masked column\n{colsums}\n')
print(f'the mean of each masked column\n{colmeans}\n')

输出:

sum of each masked column
[3.0 15.0 31.0 27.0]

the mean of each column
[1.5 7.5 15.5 9.0]

请注意,第一列的平均值计算为(1.0 + 2.0)/2。该mean方法完全忽略了被屏蔽的元素,与 OP 的原始行删除方法相同。

循环覆盖的列

如果您想要执行一些没有内置 Numpy 方法(如sumor )的计算mean,则可以改为遍历掩码列并依次对每个列进行操作,如下所示:

colmeans = [col.mean() for col in marr.T]
print(f'the result of iterating over the masked columns and taking the mean of each\n{colmeans}\n')

输出:

the result of iterating over the masked columns and taking the mean of each
[1.5, 7.5, 15.5, 9.0]

推荐阅读