编辑二维数组中元素的简单方法 Python:
a simple way to editing elements in a 2D array Python:
我希望能够对二维数组中的特定元素执行操作,前提是它符合条件。在下面的示例中,代码使任何值 < 0.5 = 0.
有谁知道这样做的简单方法吗?下面是我的代码,但我确定有更简单的方法。
import numpy as np
x = 5
y = 5
x3 = np.random.rand(x,y)
def choice(arr):
row = -1
column = -1
for i in arr:
row += 1
for j in i:
column += 1
if j >= 0.5:
arr[row,column] = j
else:
arr[row,column] = 0
if column == y - 1:
column = -1
return arr
y3 = choice(x3.copy())
将所有 < 0.5 的索引归零,
>>> x3 = np.random.rand(5, 5)
>>> x3
array([[0.50866152, 0.56821455, 0.88531855, 0.36596337, 0.08705278],
[0.96215686, 0.19553668, 0.15948972, 0.20486815, 0.74759719],
[0.36269356, 0.54718917, 0.66196524, 0.82380099, 0.77739482],
[0.0431448 , 0.47664036, 0.80188153, 0.8099637 , 0.65258638],
[0.84862179, 0.22976325, 0.03508076, 0.72360136, 0.76835819]])
>>> x3[x3 < .5] = 0
>>> x3
array([[0.50866152, 0.56821455, 0.88531855, 0. , 0. ],
[0.96215686, 0. , 0. , 0. , 0.74759719],
[0. , 0.54718917, 0.66196524, 0.82380099, 0.77739482],
[0. , 0. , 0.80188153, 0.8099637 , 0.65258638],
[0.84862179, 0. , 0. , 0.72360136, 0.76835819]])
仅用于枚举和三元条件介绍,您可以这样做:
import numpy as np
x = 5
y = 5
x3 = np.random.rand(x,y)
def choice(arr):
for row_idx, row in enumerate(arr):
for col_idx, val in enumerate(row) :
arr[row_idx,col_idx] = val if val >= 0.5 else 0
return arr
y3 = choice(x3.copy())
但 AKX 解决方案更好。
我希望能够对二维数组中的特定元素执行操作,前提是它符合条件。在下面的示例中,代码使任何值 < 0.5 = 0.
有谁知道这样做的简单方法吗?下面是我的代码,但我确定有更简单的方法。
import numpy as np
x = 5
y = 5
x3 = np.random.rand(x,y)
def choice(arr):
row = -1
column = -1
for i in arr:
row += 1
for j in i:
column += 1
if j >= 0.5:
arr[row,column] = j
else:
arr[row,column] = 0
if column == y - 1:
column = -1
return arr
y3 = choice(x3.copy())
将所有 < 0.5 的索引归零,
>>> x3 = np.random.rand(5, 5)
>>> x3
array([[0.50866152, 0.56821455, 0.88531855, 0.36596337, 0.08705278],
[0.96215686, 0.19553668, 0.15948972, 0.20486815, 0.74759719],
[0.36269356, 0.54718917, 0.66196524, 0.82380099, 0.77739482],
[0.0431448 , 0.47664036, 0.80188153, 0.8099637 , 0.65258638],
[0.84862179, 0.22976325, 0.03508076, 0.72360136, 0.76835819]])
>>> x3[x3 < .5] = 0
>>> x3
array([[0.50866152, 0.56821455, 0.88531855, 0. , 0. ],
[0.96215686, 0. , 0. , 0. , 0.74759719],
[0. , 0.54718917, 0.66196524, 0.82380099, 0.77739482],
[0. , 0. , 0.80188153, 0.8099637 , 0.65258638],
[0.84862179, 0. , 0. , 0.72360136, 0.76835819]])
仅用于枚举和三元条件介绍,您可以这样做:
import numpy as np
x = 5
y = 5
x3 = np.random.rand(x,y)
def choice(arr):
for row_idx, row in enumerate(arr):
for col_idx, val in enumerate(row) :
arr[row_idx,col_idx] = val if val >= 0.5 else 0
return arr
y3 = choice(x3.copy())
但 AKX 解决方案更好。