gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:41:43 25 4
gpt4 key购买 nike

我有一个形状为 (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com