np.array上的蒙板数组计算

时间:2013-08-16 22:11:55

标签: python multidimensional-array masking

假设,例如,我有一个Numpy nd.array,其形状为(10,10):

import numpy as np
a = np.linspace(-1,1,100).reshape(10,10)

当且仅当第一个元素小于零时,我想对每一行的第一个元素执行计算。为此,我一直在考虑使用蒙面数组:

a = np.ma.MaskedArray(a,mask=(np.ones_like(a)*(a[:,0]<0)).T)

>>> (np.ones_like(a)*(a[:,0]<0)).T
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

这将允许我仅对第一个元素小于零的行执行计算(恰好在这个例子中,这些行的其他元素也是负数,但我已经测试过了只有第一个元素是负数,其他元素是正数。我现在有几个问题:

1)我是否应该添加一个额外的掩码来覆盖除第一个之外的所有列以执行我的计算(以使示例具体:我想将1000添加到每行的第一个元素,其中该元素小于零)?

2)屏蔽数组是永久的吗?是否有取消掩码方法?

3)这是执行此类计算的最简单方法吗?

任何建议将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用pandas执行以下操作:

import numpy as np
from pandas import DataFrame  # DataFrame is the workhorse of pandas

a = DataFrame(np.linspace(-1, 1, 100).reshape(10, 10))
mask = a[0] < 0 # a[0] is the 0th column of a
suba = a[mask]

# do some calcs with suba ... make sure the index remains the same

a[mask] = suba

答案 1 :(得分:1)

在我看来,使用蒙面数组对于做一些比较简单的事情来说似乎有些过分。我会使用花哨的numpy索引来做到这一点:

#get indices of rows to update
rowsToUpdate = np.nonzero(a[:,0]<0)[0]
#increment first element of target rows by 1000
a[rowsToUpdate,0] += 1000