Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - Flatten numpy array without double for loop

I have a 2-d matrix. For the purposes of this example, let's say it is a random matrix

>>> a = np.random.randn(5, 7)
>>> a
array([[-0.37279322,  0.28619523, -0.05309901,  0.26010327,  0.1846693 , 0.33112176,  0.75814911],
       [ 1.57001151, -0.86831693, -0.20576395,  1.46450855, -0.01631132, 3.02790403, -0.65313017],
       [ 0.2362675 , -1.52190536,  0.04687194,  2.01618876,  0.03780218, -0.53041096, -0.30104844],
       [-0.5504834 ,  1.04286156,  1.12863785,  0.89583492,  0.28607363, 1.42858007,  0.28582572],
       [-0.768464  ,  0.31952554,  0.81129581,  0.26239668, -0.23242878, -1.01584339,  0.39573906]])

and two vectors of labels:

label_y = np.array([23, 984, 123, 9321, 121238])
label_x = np.array([121, 31312, 9123131, 1111, 1231441, 1929313, 192312312361])

I'd like to flatten the elements of a and output their label indeces and values. For example:

23,121,-0.37279322 
23,31312,0.28619523 
23,9123131,-0.05309901 
23,1111,0.26010327
23,1231441,0.1846693
23,1929313,0.33112176
23,192312312361,0.75814911 
984,121,...
...

is there an easy way of doing it in numpy without for loops?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use np.meshgrid to create 2D meshes corresponding to X and Y labels and then stack them as columns alongwith the 2D input array a, like so -

X,Y = np.meshgrid(label_x,label_y)
out = np.column_stack((Y.ravel(),X.ravel(),a.ravel()))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...