简体   繁体   中英

How to assign values from two matrices to each other in sequence?

I try to assign a value from the second matrix to the values in the first lubricator according to the example. First, I go through the last row in the matrix b and assign the values from the matrix d to it gradually. Then I move one line higher in the matrix b and the next position in the matrix d and I also assign successively. And so I proceed to the end of the matrix

Example

import numpy as np

b=np.array([13,14,15,16,17],
           [22,23,24,25,26],
           [31,32,33,34,35])

d=np.array[100,200,300,400,500,600,700]

required output

31 100
32 200
33 300
34 400
35 500
22 200
23 300
24 400
25 500
26 600
13 300
14 400 
15 500 
16 600
17 700

Can anyone help me with this?

**Note: I made minor fixes in syntax.
The -(negative) indexing will be useful. you need to iterate -1,-2... rows on b. -1 = last row. and use row id to get offset in d.

import numpy as np
b=np.array([[13,14,15,16,17],
           [22,23,24,25,26],
           [31,32,33,34,35]])

d=np.array([100,200,300,400,500,600,700])

for i in range(1, 1+len(b)):
    for j in range(len(b[-i])):
        print(b[-i][j], d[i+j-1])

To do that you can reorder the rows of b and stack them in sequence horizontally.
Then create a matrix from the array d by taking the element from i to i + len(row(b)), where i start from 0 and shift after each epoch, then stack the rows in sequence horizontally.
Finally you can zip the two arrays to obtain the desired result

b=np.array([[13,14,15,16,17],
           [22,23,24,25,26],
           [31,32,33,34,35]])

d=np.array([100,200,300,400,500,600,700])

val1 = np.hstack(b[::-1])
val2 = np.hstack([d[i:i+b.shape[1]] for i in range(b.shape[0])])
res = zip(val1, val2)
for i, j in res:
    print(i, j)

output:

31 100
32 200
33 300
34 400
35 500
22 200
23 300
24 400
25 500
26 600
13 300
14 400
15 500
16 600
17 700

If your indexing from d array is predicated by a array, you can try something like:

>>> order = b[::-1]
>>> idx = (order % 10) - 1
>>> np.stack([order.ravel(), d[idx].ravel()]).T

array([[ 31, 100],
       [ 32, 200],
       [ 33, 300],
       [ 34, 400],
       [ 35, 500],
       [ 22, 200],
       [ 23, 300],
       [ 24, 400],
       [ 25, 500],
       [ 26, 600],
       [ 13, 300],
       [ 14, 400],
       [ 15, 500],
       [ 16, 600],
       [ 17, 700]])

You can view d as the matrix that corresponds to the flipped b :

v = np.lib.stride_tricks.as_strided(d, shape=b.shape, strides=d.strides * 2)

Now you can stack the two together:

result = np.ravel((b[::-1].ravel(), v.ravel()), axis=-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM