Numpy > Masked array > マスクされた箇所に別のarrayの要素を入れる
概要
- マスクされた要素(
--
)を持つarrayがある - マスクされた要素に別のarrayの要素を上書きする
実装
実装
一次元にしてから処理をしている。
直接的な処理にはなっていないが、希望の動作にはなった、という程度の実装。
import numpy as np
import numpy.ma as ma
# checked with PEP8
MASKED_VALUE = -32768
SIZE_X = 3
SIZE_Y = 3
# 1. data preparation
ncep = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]])
oisst_unmask = np.array([[2, 7, 1], [8, 2, 8], [1, 8, 2]])
masks = np.array([[1, 0, 1], [1, 0, 1], [1, 0, 1]])
oisst_masked = ma.masked_where(masks, oisst_unmask)
ma.set_fill_value(oisst_masked, MASKED_VALUE)
print(ncep)
print(oisst_unmask)
print(oisst_masked)
# masked.mask = ma.nomask # unmask > values before masking
print(oisst_masked.mask)
# 2. unmasking by overwriting with ncep data
# flatten_mask = ma.MaskedArray.flatten(oisst_masked)
flatten_mask = oisst_masked.mask.flatten()
flatten_oisst = oisst_masked.flatten()
flatten_ncep = ncep.flatten()
print(flatten_mask)
for idx, elem in enumerate(flatten_oisst):
if flatten_mask[idx]:
flatten_oisst[idx] = flatten_ncep[idx]
print(flatten_oisst)
array_oisst = flatten_oisst.reshape([SIZE_X, SIZE_Y])
print(array_oisst)
結果
[[3 1 4]
[1 5 9]
[2 6 5]]
[[2 7 1]
[8 2 8]
[1 8 2]]
[[-- 7 --]
[-- 2 --]
[-- 8 --]]
[[ True False True]
[ True False True]
[ True False True]]
[ True False True True False True True False True]
[3 7 4 1 2 9 2 8 5]
[[3 7 4]
[1 2 9]
[2 8 5]]
関連
Author And Source
この問題について(Numpy > Masked array > マスクされた箇所に別のarrayの要素を入れる), 我々は、より多くの情報をここで見つけました https://qiita.com/7of9/items/b451fac8e7d762597d78著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .