python - 定义堆积条形图中每个条形的底部

标签 python arrays numpy matplotlib difference

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

1) absolute_heights[0, i] - Absolute_heights[1, i] 的符号与 absolute_heights[0, i] 的符号匹配,在这种情况下 bottoms[0, i] 应设置为 absolute_heights[1, i]

2) #1 为 false,在这种情况下,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中是否有更有效的方法来做到这一点?

最佳答案

您可以使用 bool 索引来避免 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 是一个 bool 数组,指示符号是否匹配(本质上是您的 if 语句)。使用 ~i 反转 bool 值给出 else 语句的数组。

关于python - 定义堆积条形图中每个条形的底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559179/

相关文章:

python - 通过 Python 字典元素隐式迭代

python - 选择数组中向量的分量

python - 如何打包 Django 应用程序以使其易于测试?

python - Tensorflow - 断言失败 : [predictions must be in [0, 1]]

python - web2py:多个表:有条件插入/更新/删除:从一种表单

c++ - 清除字符串数组 C++

php - 使用 array_walk() 时是否需要这种技术

Python pandas 通过检查值是否更改然后之前的值进行分组

python - TypeError: &: 'float' 和 'numpy.float64' 不支持的操作数类型

python - 使用 x 轴偏移在 python (5GB) 中绘制非常大的文件