NumPy: create a bool array, for example, "repeat", but in several dimensions

I'm looking for something like sum() , I think. Here we go:

 x = array([ [False, False, False, False, False], [ True, False, False, False, False], [ True, True, False, False, False], [ True, True, True, False, False]]) x.sum(axis=1) Out: array([0, 1, 2, 3]) 

So, I want to go in the opposite direction: from [0,1,2,3] to an array like x (I can specify the number of columns that I want in x, of course, above it 5).

The solution should work perfectly also for higher dimensions, and I certainly do not want to get stuck in Python, because the input may be longer than this example. However, here's a solution using a loop:

 s = np.array([0, 1, 2, 3]) y = np.zeros((len(s), 5), np.bool) for row,col in enumerate(s): y[row,0:col] = True 
+1
source share
1 answer

IIUC - and I'm not sure I know - you could use arange and live comparisons:

 >>> v = np.array([0,1,3,2]) >>> np.arange(5) < v[...,None] array([[False, False, False, False, False], [ True, False, False, False, False], [ True, True, True, False, False], [ True, True, False, False, False]], dtype=bool) 

or in 2D:

 >>> v = np.array([[1,2],[0,2]]) >>> np.arange(5) < v[...,None] array([[[ True, False, False, False, False], [ True, True, False, False, False]], [[False, False, False, False, False], [ True, True, False, False, False]]], dtype=bool) >>> ((np.arange(5) < v[...,None]).sum(2) == v).all() True 
+2
source

Source: https://habr.com/ru/post/976595/


All Articles