python - 在 Python 中创建具有多个给定值的掩码数组

标签 python arrays numpy mask

我正在根据同等大小的时间列绘制大量数据的几列(通过 numpy.genfromtxt)。缺失数据通常被称为 nan、-999、-9999 等。但是我不知道如何从数组中删除多个值。这是我目前拥有的:

for cur_col in range(start_col, total_col):
    # Generate what is to be graphed by removing nan values
    data_mask = (file_data[:, cur_col] != nan_values)
    y_data = file_data[:, cur_col][data_mask]
    x_data = file_data[:, time_col][data_mask]

之后,我使用 matplotlib 为每列创建适当的数字。如果 nan_values 是单个整数,则效果很好,但我希望使用列表。

编辑:这是一个工作示例。

import numpy as np

file_data = np.arange(12.0).reshape((4,3))
file_data[1,1] = np.nan
file_data[2,2] = -999
nan_values = -999

for cur_col in range(1,3):
    # Generate what is to be graphed by removing nan values
    data_mask = (file_data[:, cur_col] != nan_values)
    y_data = file_data[:, cur_col][data_mask]
    x_data = file_data[:, 0][data_mask]
    print 'y: ' + str(y_data)
    print 'x: ' + str(x_data)
print file_data

>>> y: [  1.  nan   7.  10.]
    x: [ 0.  3.  6.  9.]
    y: [  2.   5.  11.]
    x: [ 0.  3.  9.]
    [[   0.    1.    2.]
    [   3.   nan    5.]
    [   6.    7. -999.]
    [   9.   10.   11.]]

如果 nan_values = ['nan', -999] 这将不起作用,这正是我想要实现的目标。

最佳答案

我建议使用masked arrays像这样:

>>> a = np.arange(12.0).reshape((4,3))
>>> a[1,1] = np.nan
>>> a[2,2] = -999
>>> a
array([[   0.,    1.,    2.],
       [   3.,   nan,    5.],
       [   6.,    7., -999.],
       [   9.,   10.,   11.]])
>>> m = np.ma.array(a,mask=(~np.isfinite(a) | (a == -999)))
>>> m
masked_array(data =
 [[0.0 1.0 2.0]
 [3.0 -- 5.0]
 [6.0 7.0 --]
 [9.0 10.0 11.0]],
             mask =
 [[False False False]
 [False  True False]
 [False False  True]
 [False False False]],
       fill_value = 1e+20)

关于python - 在 Python 中创建具有多个给定值的掩码数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146229/

相关文章:

python - 在 plotly 中使用数值创建甘特图

ios - 如何对 JSON 数组进行排序并将其呈现在 UITableView 中

c++ - 目前正在尝试使用冒泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的。

java - 使用 Spring 自动从属性文件连接多个数组

python - 如何计算元素 x[i+1] 和 x[i-1] 之间的差异?

python - 来自opencv矩形的奇怪错误

python - 将 3D 矩阵与 2D 矩阵相乘

python - 根据已知角值估计数字矩阵?

python - Python 中的 MultiFernet 分配创建的列表

python - 如何访问集合中任意元素的属性