如果我有一个 NumPy 数组和一个行索引列表:
import numpy as np
x = np.random.rand(50).reshape(10,5)
row_idx = [0, 1, 4]
如何将 row_idx
中小于 0.5 的行中的所有值设置为零?
我试过了:
x[row_idx][x[row_idx] < 0.5] = 0.0
但这并没有起到任何作用
答案 0 :(得分:1)
您可以使用 np.where
:
In [26]: x[row_idx] = np.where(x[row_idx] < 0.5, 0, x[row_idx])
In [27]: x
Out[27]:
array([[0.94870486, 0. , 0. , 0.89030411, 0.50505295],
[0.56803186, 0.90804518, 0.69843535, 0.77174293, 0. ],
[0.1318847 , 0.95940137, 0.92036048, 0.669007 , 0.15404623],
[0.90021311, 0.72959638, 0.82705006, 0.65329554, 0.3714969 ],
[0.56293165, 0. , 0. , 0. , 0. ],
[0.46015752, 0.96294812, 0.0678065 , 0.66693152, 0.69825679],
[0.63310433, 0.59532105, 0.75913618, 0.60258213, 0.48668606],
[0.69935925, 0.15807776, 0.8589115 , 0.37657828, 0.69651669],
[0.87587399, 0.68772743, 0.59854082, 0.67857679, 0.34182774],
[0.3734155 , 0.06255165, 0.02622334, 0.17993743, 0.1783275 ]])