【问题标题】:Define the bottom of each bar in a stacked bar graph定义堆叠条形图中每个条形的底部
【发布时间】:2015-05-31 15:30:51
【问题描述】:

我有一个二维数组absolute_heights,形状为(2, 6)。我想定义一个形状为(2, 6) 的新二维数组bottoms,它在每个位置0 处保存i,除非

1) absolute_heights[0, i] - absolute_heights[1, i] 的符号与absolute_heights[0, i] 的符号匹配,此时bottoms[0, i] 应设置为absolute_heights[1, i]。

2) #1 为假,此时bottoms[1, i] 应设置为absolute_heights[0, i]。

下面是实现此目的的for 循环:

def _get_bottoms(absolute_heights):
    """Define the bottom of each bar in a stacked bar graph.

    Parameters
    ----------
    absolute_heights : np.array
      The absolute height of each bar.  Stacking of the bars is along
      the first axis of this array.

    Returns
    -------
    bottoms : np.array
      The absolute height of the bar in each stack that is closest to
      zero.

    """
    bottoms = np.zeros((2, 6))
    for i, diff in enumerate(absolute_heights[0, :] - absolute_heights[1, :]):
        if np.sign(diff) == np.sign(absolute_heights[0, i]):
            bottoms[0, i] = absolute_heights[1, i]
        else:
            bottoms[1, i] = absolute_heights[0, i]
    return bottoms

numpy 中是否有更有效的方法?

【问题讨论】:

    标签: python arrays numpy matplotlib difference


    【解决方案1】:

    您可以使用布尔索引来避免for 循环:

    def _get_bottoms(absolute_heights):
        bottoms = np.zeros((2,6))
        diff = absolute_heights[0, :] - absolute_heights[1, :]
        i = np.sign(diff) == np.sign(absolute_heights[0, :])
        bottoms[0, i] = absolute_heights[1, i]
        bottoms[1, ~i] = absolute_heights[0, ~i]
        return bottoms
    

    在此函数中,i 是一个布尔数组,指示符号是否匹配(本质上是您的 if 语句)。将布尔值与 ~i 取反后得到 else 语句的数组。

    【讨论】:

    • 我在原始问题中犯了一个错误。查看更新。
    • @dbliss:我已经相应地更新了我的答案。它给出的答案与您在测试数组上的函数相同。
    【解决方案2】:

    使用 np.where 的另一种解决方案

    b = np.where(np.sign(ah[0,:]) == np.sign(ah[0,:] - ah[1,:]), ah[1,:], 0.)
    b2 = np.where(np.sign(ah[0,:]) != np.sign(ah[0,:] - ah[1,:]), ah[0,:], 0.)
    np.vstack((b2,b))
    

    不太可能比上面提到的快很多,可能 - 可读性略高。

    np.where 接受一个布尔条件数组,然后如果条件为真则使用第一个参数(上面的ah[1,:]),否则使用第二个参数(上面的ah[0,:])。

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多