按列获取非零且非 NaN 的元素。

huangapple go评论78阅读模式
英文:

get non-zero and not-nan elements column wise

问题

import numpy as np

我有一个numpy数组如下

data = np.array([[2, 3, 4, 5, 0, 7, 8, 9, 9, 3, np.nan],
                 [3, 3, 6, 5, 0, 7, 9, 9, 9, 3, 1],
                 [2, 6, 4, 5, 0, 7, 9, 9, 9, 4, 1]])
print(data)

我想从中获取所有数字按列不为0的数据以及从中任何元素不为np.nan的数据

indices = np.any(data, axis=1)

print(data[indices])

期望结果是

[[2 3 4 5 7 8 9 9 3]
 [3 3 6 5 7 9 9 9 3]
 [2 6 4 5 7 9 9 9 4]]

我尝试了如下的掩码

mask = np.all(np.isnan(data) | np.equal(data, 0), axis=1)

print(data[~mask])

但不是预期的结果。

英文:
import numpy as np

I have a numpy array follows:

data = np.array([[2,3,4,5,0,7,8,9,9,3,np.nan],
                 [3,3,6,5,0,7,9,9,9,3,1],
                 [2,6,4,5,0,7,9,9,9,4,1]])
print (data)

I wanted to get the data from where all numbers (column wise) are not 0; and from where any elements are not np.nan.

indices = np.any(data, axis=1)

print (data[indices])

expected is:

[[2 3 4 5 7 8 9 9 3]
 [3 3 6 5 7 9 9 9 3]
 [2 6 4 5 7 9 9 9 4]]

I tried as mask as follows.

mask = np.all(np.isnan(data) | np.equal(data, 0), axis=1)

print (data[~mask])



[[ 2.  3.  4.  5.  0.  7.  0.  9.  9.  3. nan]
 [ 3.  3.  6.  5.  0.  7.  9.  9.  9.  3.  1.]
 [ 2.  6.  4.  5.  0.  7.  9.  9.  9.  4.  1.]]

but not expected result

答案1

得分: 1

使用np.any沿着列(axis=0)进行操作。将其与np.isnan的否定组合使用。这将返回列索引,其中该列中的任何值都不为零且没有NaN值。然后,使用这些索引来索引原始数组。

mask = ~np.any(np.isnan(data), axis=0) & np.any(data, axis=0)
indices = data[:, mask]
英文:

use np.any along the columns (axis=0). Combine this with not any np.isnan
This will return column indices where any value in that column is not zero and there are no nans.
Then use these to index the original array.

mask = ~np.any(np.isnan(data),axis=0) &  np.any(data, axis=0)
indices=data[:,mask]

答案2

得分: 1

data[:, (~np.isnan(data)).all(axis=0) & ~(data == 0).any(axis=0)].astype("int")

输出:

[[2 3 4 5 7 8 9 9 3]
 [3 3 6 5 7 9 9 9 3]
 [2 6 4 5 7 9 9 9 4]]
英文:

You can do:

data[:,(~np.isnan(data)).all(axis=0)&~(data==0).any(axis=0)].astype("int")

Output:

[[2 3 4 5 7 8 9 9 3]
 [3 3 6 5 7 9 9 9 3]
 [2 6 4 5 7 9 9 9 4]]

huangapple
  • 本文由 发表于 2020年1月4日 01:20:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定