这是一条路-
def mask_from_indices(indices, ncols=None):
# Extract column indices
col_idx = np.concatenate(indices)
# If number of cols is not given, infer it based on max column index
if ncols is None:
ncols = col_idx.max()+1
# Length of indices, to be used as no. of rows in o/p
n = len(indices)
# Initialize o/p array
out = np.zeros((n,ncols), dtype=bool)
# Lengths of each index element that represents each group of col indices
lens = np.array(list(map(len,indices)))
# Use np.repeat to generate all row indices
row_idx = np.repeat(np.arange(len(lens)),lens)
# Finally use row, col indices to set True values
out[row_idx,col_idx] = 1
return out
样品运行-
In [89]: mask_from_indices(indices)
Out[89]:
array([[ True, False, True, False, False, False, False, False],
[ True, False, False, False, False, False, False, False],
[False, True, False, False, True, False, False, True]])