一种在二维数组 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())


繁花不似锦
浏览 86回答 2
2回答

湖上湖

要将所有 < 0.5 的索引归零,>>> x3 = np.random.rand(5, 5)>>> x3array([[0.50866152, 0.56821455, 0.88531855, 0.36596337, 0.08705278],&nbsp; &nbsp; &nbsp; &nbsp;[0.96215686, 0.19553668, 0.15948972, 0.20486815, 0.74759719],&nbsp; &nbsp; &nbsp; &nbsp;[0.36269356, 0.54718917, 0.66196524, 0.82380099, 0.77739482],&nbsp; &nbsp; &nbsp; &nbsp;[0.0431448 , 0.47664036, 0.80188153, 0.8099637 , 0.65258638],&nbsp; &nbsp; &nbsp; &nbsp;[0.84862179, 0.22976325, 0.03508076, 0.72360136, 0.76835819]])>>> x3[x3 < .5] = 0>>> x3array([[0.50866152, 0.56821455, 0.88531855, 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp;[0.96215686, 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.74759719],&nbsp; &nbsp; &nbsp; &nbsp;[0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.54718917, 0.66196524, 0.82380099, 0.77739482],&nbsp; &nbsp; &nbsp; &nbsp;[0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.80188153, 0.8099637 , 0.65258638],&nbsp; &nbsp; &nbsp; &nbsp;[0.84862179, 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.&nbsp; &nbsp; &nbsp; &nbsp; , 0.72360136, 0.76835819]])

眼眸繁星

仅针对枚举和三元条件介绍,您可以执行以下操作:import numpy as npx = 5y = 5x3 = np.random.rand(x,y)def choice(arr):&nbsp; &nbsp; for row_idx, row in enumerate(arr):&nbsp; &nbsp; &nbsp; &nbsp; for col_idx, val in enumerate(row) :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[row_idx,col_idx] = val if val >= 0.5 else 0&nbsp; &nbsp; return arry3 = choice(x3.copy())但是 AKX 解决方案更好。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python