【发布时间】:2014-07-29 07:07:46
【问题描述】:
我正在尝试使用time、lat、lon 的数组创建一个出现频率图。我应该得到一个二维lat/lon 频率数组。下面的代码概述了我的方法,当我将反转的布尔数组掩码转换为数值时,我在步骤 d 遇到了问题。我不小心找到了一种方法,但我不知道它为什么有效(np.mean)。我不明白为什么np.mean 将布尔值转换为浮点数,但实际上并没有计算沿请求轴的平均值。我不得不再次申请np.mean 以获得所需的结果。我觉得必须有正确的方法将布尔数组转换为浮点数或整数。另外,如果你能想出更好的方法来完成任务,那就开火吧。我的 numpy mojo 很弱,这是我能想到的唯一方法。
import numpy as np
# test 3D array in time, lat, lon; values are percents
# real array is size=(30,721,1440)
a = np.random.random_integers(0,100, size=(3,4,5))
print(a)
# Exclude all data outside the interval 0 - 20 (first quintile)
# Repeat for 21-40, 41-60, 61-80, 81-100
b = np.ma.masked_outside(a, 0, 20)
print "\n\nMasked array: "
print(b)
# Because mask is false where data within quintile, need to invert
c = [~b.mask]
print "\n\nInverted mask: "
print(c)
# Accidental way to turn True/False to 1./0., but that's what I want
d = np.mean(c, axis = 0)
print "\n\nWhy does this work? How should I be doing it?"
print(d)
# This is the mean I want. Gives desired end result
e = np.mean(d, axis = 0)
print "\n\nFrequency Map"
print(e)
如何将我的(反转)数组掩码中的布尔值转换为数字(1 和 0)?
【问题讨论】:
标签: python arrays numpy boolean