python - 如何用 numpy 的行平均值替换丢失/屏蔽的数据

标签 python numpy missing-data

如何将下面“b”数组中的缺失值替换为“c”中相应的行平均值?

a=numpy.arange(24).reshape(4,-1)
b=numpy.ma.masked_where(numpy.remainder(a,5)==0,a);b
Out[46]: 
 masked_array(data =
 [[-- 1 2 3 4 --]
 [6 7 8 9 -- 11]
 [12 13 14 -- 16 17]
 [18 19 -- 21 22 23]],
         mask =
 [[ True False False False False  True]
 [False False False False  True False]
 [False False False  True False False]
 [False False  True False False False]],
       fill_value = 999999)

c=b.mean(axis=1);c
Out[47]: 
masked_array(data = [2.5 8.2 14.4 20.6],
         mask = [False False False False],
   fill_value = 1e+20)

最佳答案

试试这个:

np.copyto(b, c[...,None], where=b.mask)

您必须将额外的轴添加到c,以便它知道将其应用到每一行。 (如果 np.mean 有一个像 np.sum 这样的 keepdims 选项,则没有必要:P

import numpy as np

a = np.arange(24).reshape(4,-1).astype(float)   # I changed your example to be a float
b = np.ma.masked_where(numpy.remainder(a,5)==0,a)
c = b.mean(1)

np.copyto(b, c[...,None], where=b.mask)

In [189]: b.data
Out[189]: 
array([[  2.5,   1. ,   2. ,   3. ,   4. ,   2.5],
       [  6. ,   7. ,   8. ,   9. ,   8.2,  11. ],
       [ 12. ,  13. ,  14. ,  14.4,  16. ,  17. ],
       [ 18. ,  19. ,  20.6,  21. ,  22. ,  23. ]])

这比创建 inds 数组更快:

In [169]: %%timeit
   .....: inds = np.where(b.mask)
   .....: b[inds] = np.take(c, inds[0])
   .....: 
10000 loops, best of 3: 81.2 µs per loop


In [173]: %%timeit
   .....: np.copyto(b, c[...,None], where=b.mask)
   .....: 
10000 loops, best of 3: 45.1 µs per loop

另一个优点是它会警告您有关数据类型的问题:

a = np.arange(24).reshape(4,-1)    # still an int
b = np.ma.masked_where(numpy.remainder(a,5)==0,a)
c = b.mean(1)

In [193]: np.copyto(b, c[...,None], where=b.mask)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-193-edc7f01f3f89> in <module>()
----> 1 np.copyto(b, c[...,None], where=b.mask)

TypeError: Can not cast scalar from dtype('float64') to dtype('int64') according to the rule 'same_kind'

顺便说一句,有一组函数可以完成此类任务,具体取决于您拥有的不同源格式,例如

np.put
按顺序将输入数组放入索引给定位置的输出数组中,并且像 @Ophion 的答案一样工作。

np.place
顺序将输入(列表或一维数组)中的每个元素分配到输出数组中掩码为 true 的位置(不与输入数组对齐,因为它们的形状不必匹配)。

np.copyto
总是将输入数组中的值放入输出数组中的相同(广播)位置。形状必须匹配(或可广播)。它有效地取代了旧功能 np.putmask .

关于python - 如何用 numpy 的行平均值替换丢失/屏蔽的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688038/

相关文章:

python - numpy.transpose 的时间复杂度

python - 如何在每个组中估算 Pandas 数据框中的一列

r - 计算不包含 `NA` 的数据帧的行数

python - Django-filter 'icontains' 没有传递到我的 URL

python - 管理员模拟 Django 用户

python - 将数据框中的非数字转换为 NaN (numpy)?

numpy - pykalman:(默认)处理缺失值

python - 为什么 SQLite 会插入重复的复合主键?

python - Django : is it better to import variables from a settings. py文件,还是基本配置文件?

Python-根据平均值将递增的类分配给列表val