简体   繁体   English

在 Numpy 中的阵列上应用掩码

[英]Apply Mask on an Array in Numpy

I have a problem I can't figure out and I hope you can help me.我有一个我无法弄清楚的问题,希望你能帮助我。 Assume I have an array with the shape of 146,243, I have about 144 of therm.假设我有一个形状为 146,243 的数组,我有大约 144 个。 (12 months for 12 years) There are certain indexes which always should have np.nan values and I want them always to contain nan-Values, but I have no idea how. (12 个月,12 年)有些索引总是应该有 np.nan 值,我希望它们总是包含 nan-Values,但我不知道如何。 I have come thus far.我已经到此为止了。 (This example has the right shape but there are just two occurences for np.nan, I have much more in my actual array.) (此示例具有正确的形状,但 np.nan 仅出现两次,我的实际数组中有更多。)

import numpy as np

rand_array = np.random.rand(146,243)
# In every new array those positions should always be np.nan
rand_array[0][90] = np.nan
rand_array[12][15] = np.nan
# Searching for nan-Values
nan_vals = np.argwhere(np.isnan(rand_array))

# Next Iteration
rand_array_2 = np.random.rand(146,243)
# Apply the nan values at the position found by nan_vals to rand_array_2 at the same positions

This example is quite easy and I could just manually set the nan.values but my problem array has far too many values for this method to be feasable.这个例子很简单,我可以手动设置 nan.values 但我的问题数组的值太多,这种方法不可行。 How would I go on about from finding out once where the np.nan Values are, to applying them to every consecutive array?我将如何 go 从找出 np.nan 值的位置到将它们应用于每个连续数组? Since I have the position of them saved in nan_vals I just need to figure out how to apply it to another array.由于我将其中的 position 保存在 nan_vals 中,因此我只需要弄清楚如何将其应用于另一个数组。

Kind regards.亲切的问候。

Numpy provides very much feasibilty. Numpy 提供了非常多的可行性。

You could use:你可以使用:

rand_array_2[nan_vals[:, 0], nan_vals[:, 1]] = np.nan

This will set (for your given example) rand_array_2[0, 90] and rand_array_2[12, 15] as nan这将(对于您给定的示例) rand_array_2[0, 90]rand_array_2[12, 15]nan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM