Python:划分非无的数组元素
请对我宽容一点,我不是程序员,只是个医科学生。我做下面的手术有困难 self.longitude是一个列表: self.longitude=[无,无,1,7,3,4,…]Python:划分非无的数组元素,python,numpy,Python,Numpy,请对我宽容一点,我不是程序员,只是个医科学生。我做下面的手术有困难 self.longitude是一个列表: self.longitude=[无,无,1,7,3,4,…] self.longitude = np.array(self.longitude) self.longitude = np.where(self.longitude is None, None, self.longitude/11930465) 看起来很简单,但它会引发以下异常: 显然,解释器仍在尝试对None值进
self.longitude = np.array(self.longitude)
self.longitude = np.where(self.longitude is None, None, self.longitude/11930465)
看起来很简单,但它会引发以下异常:
显然,解释器仍在尝试对None值进行除法。因此我假设numpy.where()
首先对数组执行操作,然后才替换条件值
如果有人能为我想做的事情提供一个可靠的解决方案,而不涉及到一个循环,这似乎不是很有效
提前非常感谢。您可以执行以下操作
self.longitude[np.where(self.longitude != None)] /= 11930465
这将通过
11930465
对self.longitude
的not None元素进行适当的划分。我怀疑您想要划分numpy数组的所有非None值。
您可以尝试为这些设置创建掩码,然后使用该掩码在阵列上执行操作:
import numpy as np
longitudes = np.array([None, 1, 2, None, 5])
nonNoneMask = longitudes!=None
longitudes[nonNoneMask] /= 11930465
print(longitudes)
print(longitudes[nonNoneMask])
请注意,我使用的是
!=None
而不是是None
。相等操作由要按元素执行的numpy数组重载,而is
将检查操作的两侧是否为同一对象。如果self.longtudence
包含数字或None
,则使用是安全的=代码>:
longtitude = [None,None,1,2,3,4]
longtitude = np.array(longtitude)
longtitude = longtitude[longtitude != None] / 11930465
或者,如果希望保留“无”值:
longtitude[longtitude != None] =/ 11930465
请注意,如果它将包含其他值,然后包含None
和数字(特别是对象),则不一定安全。首先,对函数的参数进行求值。其中一个参数是self.longitude/11930465
,由于self.longitude
是None
,因此失败。即使它没有失败(如果self.longitude
不是None
),这也不会起作用,因为它会调用numpy.where(False,None,self.longitude/11930465)
No,self.longitude是一个包含一些非类型值和一些整数的numpy数组。也许我应该澄清一下,那一行的错误是TypeError:unsupported操作数类型为/:'NoneType'和'int'
。因此,self.longitude
是None
。。。。。谢谢,这把我搞糊涂了。事实上,经度是没有的,我甚至不认为这就是为什么整个事情都把我甩得这么厉害……如果你找到一个能解决你问题的答案,你可以把它标记为已回答,以供将来的读者阅读。
longtitude[longtitude != None] =/ 11930465