在numpy dnarray中处理NaN / Inf

时间:2020-07-20 12:31:47

标签: python arrays numpy multidimensional-array array-indexing

处理4D numpy数组(数组数组)。每个嵌套数组的形状为(1, 100, 4)

trainset.shape
(159984, 1, 100, 4)

但是随后在嵌套数组中找到了我要处理的一些nan值。例如trainset中的第一个嵌套数组包含以下内容:

trainset[0]
array([[[ 7.10669020e-02,  4.91383899e-03, -1.43700407e-02,
          1.52228864e-04],
        [ 7.59807410e-02, -9.45620170e-03,             nan,
          1.35892100e-04],
        [ 6.65245393e-02,             nan,             nan,
          8.98521456e-05],
        [            nan,             nan,             nan,
          1.41090006e-05],
        [            nan,             nan,             nan,
          6.68319391e-06],
        [            nan,             nan,             nan,
         -3.27272689e+01],
        [            nan,             nan,             nan,
         -1.09090911e+01],
        [            nan,             nan,             nan,
          8.25973981e+01],
        [            nan,             nan,             nan,
          1.12207785e+02],
        [            nan,             nan,             nan,
          1.65194797e+02],
        [            nan,             nan,             nan,
          2.25974015e+02],
        [            nan,             nan,             nan,
          2.78961026e+02],
        [ 3.87926649e-03,  1.81274134e-04, -1.08764481e-03,
          3.41298685e+02],
        ...
        [ 4.06054062e-03, -9.06370679e-04,  1.30517379e-03,
          3.10129855e+02]]])

如何检查trainset中所有数组的nan值,并在找到的地方将其替换为列的中值?

编辑

使用:

from sklearn.impute import SimpleImputer
imp_mean = SimpleImputer(missing_values=np.nan, strategy='median')

for data in trainset:
  trainsfrom_data = imp_mean.fit(trainset)

ValueError: Found array with dim 3. Estimator expected <= 2.

给出上述指示的错误。

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用SimpleImputer,然后选择median插补策略。我不确定nan是按列替换还是按行替换,您可能必须先对数组进行整形,然后再通过SimpleImputer(),然后再将其整形。

进行编辑:将数组重塑为2D,保留列大小,然后重塑为原始形式。另外,对每一列都使用fit_transform来一次性获得结果。重塑将是这样的:

import numpy as np

A = np.random.rand(15, 1, 100, 4)
print(A.shape)

init_shape = A.shape

B = A.reshape(np.prod(init_shape[:-1]), init_shape[-1])
print(B.shape)

# SimpleImputer goes here

B = B.reshape(init_shape)
print(B.shape)