使用某些条件替换numpy数组中的元素

时间:2017-08-06 15:48:10

标签: python arrays numpy conditional-statements

例如,我有一些数组:

recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
MyAdapter adapter = new MyAdapter(verticalShownData, this.getActivity());
recyclerView.setAdapter(adapter);

recyclerView.addOnScrollListener(new HideShowScrollListener() {
     @Override
     public void onHide() {
          animateCallback.animateHide();
     }

     @Override
     public void onShow() {
          animateCallback.animateShow();
     }
});

如何将>>> x = np.arange(-5, 4).reshape(3, 3) >>> x array([[-5, -4, -3], [-2, -1, 0], [ 1, 2, 3]]) 替换为b以上的所有元素,否则将其设置为a

我试过

0

但它没有成功。

2 个答案:

答案 0 :(得分:2)

您可以使用numpy.where

x = np.arange(-5, 4).reshape(3, 3)
x
#array([[-5, -4, -3],
#       [-2, -1,  0],
#       [ 1,  2,  3]])

b = 1; a = 0;
np.where(x > a, b, 0)
#array([[0, 0, 0],
#       [0, 0, 0],
#       [1, 1, 1]])

答案 1 :(得分:1)

不如np.where好,但在您的情况下,您可以简单地将您的数组与ab进行比较时得到的“布尔数组”:

>>> x = np.arange(-5, 4).reshape(3, 3)
>>> a, b = 0, 6
>>> (x > a) * b
array([[0, 0, 0],
       [0, 0, 0],
       [6, 6, 6]])

这是有效的,因为True在算术运算中相当于1False0