说我有一个numpy数组有一些浮点数('南'),我不想现在推算这些数据,我想先对这些数据进行归一化处理,并将NaN数据保留在原始空间,有没有办法可以做到吗?如何忽略numpy数组中的NaN数据点并在Python中生成规范化数据?
此前我在sklearn.Preprocessing
中使用了normalize
函数,但该函数似乎不能将任何含有NaN的数组作为输入。
说我有一个numpy数组有一些浮点数('南'),我不想现在推算这些数据,我想先对这些数据进行归一化处理,并将NaN数据保留在原始空间,有没有办法可以做到吗?如何忽略numpy数组中的NaN数据点并在Python中生成规范化数据?
此前我在sklearn.Preprocessing
中使用了normalize
函数,但该函数似乎不能将任何含有NaN的数组作为输入。
您可以使用numpy.ma.array
功能掩盖你的阵列,并随后将任何numpy
操作:
import numpy as np
a = np.random.rand(10) # Generate random data.
a = np.where(a > 0.8, np.nan, a) # Set all data larger than 0.8 to NaN
a = np.ma.array(a, mask=np.isnan(a)) # Use a mask to mark the NaNs
a_norm = a/np.sum(a) # The sum function ignores the masked values.
a_norm2 = a/np.std(a) # The std function ignores the masked values.
您仍然可以访问原始数据:
print a.data
您可以使用numpy.nansum
计算标准并忽略南:
In [54]: x
Out[54]: array([ 1., 2., nan, 3.])
这里是与nan
忽略了规范:
In [55]: np.sqrt(np.nansum(np.square(x)))
Out[55]: 3.7416573867739413
y
是归一化数组:
In [56]: y = x/np.sqrt(np.nansum(np.square(x)))
In [57]: y
Out[57]: array([ 0.26726124, 0.53452248, nan, 0.80178373])
In [58]: np.linalg.norm(y[~np.isnan(y)])
Out[58]: 1.0
你的问题不明确。你是否想用NaN标准化一个数组,并忽略NaN? – Chiel
我想忽略NaNs – xxx222