python - Combine list of numpy arrays and reshape -
i'm hoping me following. have 2 lists of arrays, should linked each-other. each list stands object. arr1
, arr2
attributes of object. example:
import numpy np arr1 = [np.array([1, 2, 3]), np.array([1, 2]), np.array([2, 3])] arr2 = [np.array([20, 50, 30]), np.array([50, 50]), np.array([75, 25])]
the arrays linked each other in 1
in arr1
, first array belongs 20
in arr2
first array. result i'm looking in example numpy array size 3,4. 'columns' stand 0, 1, 2, 3 (the numbers in arr1, plus 0) , rows filled corresponding values of arr2. when there no corresponding values cell should 0. example:
array([[ 0, 20, 50, 30], [ 0, 50, 50, 0], [ 0, 0, 75, 25]])
how link these 2 list of arrays , reshape them in desired format shown in above example?
many thanks!
here's almost* vectorized approach -
lens = np.array([len(i) in arr1]) n = len(arr1) row_idx = np.repeat(np.arange(n),lens) col_idx = np.concatenate(arr1) m = col_idx.max()+1 out = np.zeros((n,m),dtype=int) out[row_idx,col_idx] = np.concatenate(arr2)
*: because of loop comprehension @ start, should computationally negligible doesn't involve computation there.
Comments
Post a Comment