【问题标题】:python array operation with index带索引的python数组操作
【发布时间】:2021-09-19 16:51:41
【问题描述】:

我尝试设计一个数组操作,描述如下:

如果数组中的元素小于 0,则新值应设置为 0。 否则新值应该是原始值的平方。

e.g.
import numpy as np
input = np.array([-2, 5, 2, -1])
#some operation ...
#input should be: [0, 25, 4, 0]

另外,我想让这个操作可以任意输入维度(2D数组,3D数组...)

我只能想到这个解决方案:

input = np.array([-2, 5, 2, -1])
input[input < 0] = 0  # input = [0 5 2 0]
#input[input >= 0] = input*input   <- this will cause error

我已经知道如何完成否定部分,但我不知道如何处理方形部分,有人可以帮助我吗?

非常感谢!

【问题讨论】:

    标签: python arrays numpy indexing conditional-statements


    【解决方案1】:

    只需使用 numpy 的 where 函数:

    output = np.where(input <= 0, 0, input**2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 2012-04-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 2014-01-15
      • 2013-11-04
      相关资源
      最近更新 更多