[英]Define the bottom of each bar in a stacked bar graph
I have a two-dimensional array absolute_heights
of shape (2, 6)
. 我有一个形状为(2, 6)
的二维数组absolute_heights
。 I'd like to define a new two-dimensional array bottoms
of shape (2, 6)
that holds 0
at each position i
unless 我想定义一个新的形状为(2, 6)
的二维数组bottoms
,在每个位置i
都保持0
,除非
1) The sign of absolute_heights[0, i] - absolute_heights[1, i]
matches that of absolute_heights[0, i]
, in which case bottoms[0, i]
should be set to absolute_heights[1, i]
. 1)的符号absolute_heights[0, i] - absolute_heights[1, i]
匹配的absolute_heights[0, i]
在这种情况下, bottoms[0, i]
应被设置为absolute_heights[1, i]
2) #1 is false, in which case bottoms[1, i]
should be set to absolute_heights[0, i]
. 2)#1为假,在这种情况下, bottoms[1, i]
应设置为absolute_heights[0, i]
。
Below is a for
loop that achieves this: 下面是一个实现此目的的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
Is there a more efficient way of doing this in numpy
? 在numpy
有更有效的方法吗?
You could use boolean indexing to avoid the for
loop: 您可以使用布尔索引来避免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
In this function i
is a boolean array indicating whether the signs match (essentially your if
statement). 在此函数中, i
是一个布尔数组,指示符号是否匹配(本质上是if
语句)。 Inverting the boolean values with ~i
gives the array for the else
statement. 反转布尔值与~i
给出了数组else
声明。
Another solution using np.where 使用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))
Unlikely to be substantially faster than the one mentioned above, possibly - slightly more readable. 不可能比上述提到的要快得多,但可能-可读性更高。
np.where
takes an array of bool conditions and then uses the first argument ( ah[1,:]
above) if the condition is True else second argument( ah[0,:]
above). np.where
接受布尔条件数组,如果条件为True,则使用第一个参数(上面的ah[1,:]
),否则使用第二个参数(上面的ah[0,:]
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.