Element-wise broadcasting for comparing two NumPy arrays?

后端 未结 3 808
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 04:54

Let\'s say I have an array like this:

import numpy as np

base_array = np.array([-13, -9, -11, -3, -3, -4,   2,  2,
                         2,  5,   7,  7,          


        
3条回答
  •  余生分开走
    2021-01-19 05:29

    You can simply add a dimension to the comparison array, so that the comparison is "stretched" across all values along the new dimension.

    >>> np.sum(comparison_array[:, None] < base_array)
    228
    

    This is the fundamental principle with broadcasting, and works for all kinds of operations.

    If you need the sum done along an axis, you just specify the axis along which you want to sum after the comparison.

    >>> np.sum(comparison_array[:, None] < base_array, axis=1)
    array([15, 15, 14, 14, 13, 13, 13, 13, 13, 12, 10, 10, 10, 10, 10,  7,  7,
            7,  6,  6,  3,  2,  2,  2,  1,  0])
    

提交回复
热议问题