python - 在矩阵中使用 numpy.sum 和 numpy.mean 时如何忽略值

标签 python numpy sum mean

在 numpy 中应用 sum 和 mean 时,有没有办法避免使用特定值?

例如,我想在计算结果时避免使用 -999 值。

In [14]: c = np.matrix([[4., 2.],[4., 1.]])

In [15]: d = np.matrix([[3., 2.],[4., -999.]])

In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[   7.,    4.],
       [   8., -998.]])

In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[   3.5,    2. ],
       [   4. , -499. ]])

最佳答案

使用屏蔽数组:

>>> c = np.ma.array([[4., 2.], [4., 1.]])
>>> d = np.ma.masked_values([[3., 2.], [4., -999]], -999)

>>> np.ma.array([c, d]).sum(axis=0)
masked_array(data =
 [[7.0 4.0]
 [8.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

>>> np.ma.array([c, d]).mean(axis=0)
masked_array(data =
 [[3.5 2.0]
 [4.0 1.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

关于python - 在矩阵中使用 numpy.sum 和 numpy.mean 时如何忽略值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913275/

相关文章:

python - 在 Python 中,如何缩放存储为 NumPy 数组的图像的大小?

python - 在 Python 中对数组的各个部分求平均值

mysql - 我的sql字段总和使用另一个字段来区分然后排序

function - 可变数量和函数的正确行为

sqlite - 如何在 SQLite 中添加总列

python - 如何使用 matplotlib 绘制复杂的条形图——具有多行条形的多个子图?

python - async_generator block

python - 对 numpy 数组进行子采样/平均

python - 根据两列的值选择 Pandas 数据框行

python - 将 ascii 字符转换为带符号的 8 位整数 python