英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论