arrays - 索引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
我想学习一种新的方法来完成我的任务。非常感谢。
解决方案
解决方案:使用掩码数组
考虑到 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]]
一次对掩码数组中的所有列进行操作,无需循环
然后,您可以一次对所有被屏蔽的列执行各种操作(sum
、mean
、cumprod
等),如下所示:
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 方法(如sum
or )的计算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]
推荐阅读
- python - 如何从numpy数组中获取N条记录?
- ruby - RSpec - 如何修复 - ArgumentError:参数数量错误(给定 0,预期为 1) - Ruby
- graphql - graphql sequlize 数据加载器问题,无法为不可为空的字段返回 null
- mysql - 如何显示没有特定值的行?
- r - R中的外部函数调用(arg 1)中的NA / NaN / Inf
- javascript - 在 Angular 中使用 ngFor 在 div 之间画一条线
- postgresql - Docker-compose:Postgresql ECONNREFUSED
- python - 我想使用 fillna 均值来填充缺失值。我想根据产品 ID 来做
- r - R 包 - 二进制 (tar.gz)
- php - 我网站的 Facebook 日志帐户的会话仍然存在