I have an array of values A
, an X
array and a Y
array:
A=np.random.rand(100)
X=np.linspace(0,9.9,100).astype('int')
Y=np.mod(np.linspace(0,99,100).astype('int'),10)
from sklearn.utils import shuffle
X, Y = shuffle(X, Y, random_state=0)
Is there a fast way without using a for
loop, to build the array B
so that B[X[i],Y[i]]=A[i]
?
CodePudding user response:
If you don't mind using additional libraries, you could use Scipy to create a sparse matrix and convert it to numpy array.
import scipy
B = scipy.sparse.coo_matrix((A, (X,Y))).toarray()
Gives you:
array([[0.72165902, 0.52990391, 0.09793563, 0.50304214, 0.1220594 ,
0.21866079, 0.21402 , 0.10083007, 0.02413508, 0.47135903],
[0.66857096, 0.53983909, 0.77737883, 0.51930043, 0.82780692,
0.49366086, 0.00985082, 0.69271283, 0.05050557, 0.13781565],
[0.55825277, 0.23288426, 0.32808517, 0.04021886, 0.62240996,
0.35775835, 0.18166671, 0.72845399, 0.82937063, 0.44513946],
[0.43459875, 0.91125147, 0.0997432 , 0.27235194, 0.51298843,
0.51844005, 0.24192413, 0.87119785, 0.35759919, 0.97350304],
[0.76596234, 0.0454183 , 0.7452377 , 0.99293005, 0.46079918,
0.77791926, 0.01981786, 0.79152577, 0.29018054, 0.28989354],
[0.21862015, 0.55044776, 0.41118987, 0.28499734, 0.83900364,
0.25426192, 0.98742121, 0.43742215, 0.08900043, 0.19032915],
[0.34900342, 0.34423692, 0.25362518, 0.14360852, 0.22580151,
0.29163466, 0.30428173, 0.84232247, 0.04396114, 0.3534083 ],
[0.65250231, 0.7090245 , 0.30458176, 0.51372318, 0.89439072,
0.74326644, 0.28444398, 0.2566198 , 0.70270672, 0.40769932],
[0.66205028, 0.20791073, 0.99532769, 0.69981262, 0.0782375 ,
0.24892482, 0.29280819, 0.3020104 , 0.62367672, 0.98863622],
[0.13194516, 0.8298722 , 0.31361851, 0.98307841, 0.08061206,
0.1239905 , 0.03836026, 0.52931279, 0.5748074 , 0.69816216]])