根據 numpy/python 中的條件選擇行

安德魯戈恩

我生成一個正態分佈和大小為 4x4 的隨機矩陣;然後我必須選擇總和大於 0 的行。

當我使用 2D 索引編寫代碼時,輸出似乎不正確:

a = np.random.randn(4, 4)
a[a[:, 0] > 0]

我缺少什麼?

威基基

嘗試將np.wherenp.sum結合使用

import numpy as np

np.random.seed(0)
a = np.random.randn(4, 4)
indices = np.where(np.sum(a, axis=1) > 0)
print(a[indices])  # rows with sum > 0

https://numpy.org/doc/stable/reference/generated/numpy.where.html

https://numpy.org/doc/stable/reference/generated/numpy.sum.html

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章