0

I have two 2D arrays, I want to create arrays that are copy of the first one and then replace some columns by others from the second one.

M1 = np.array([[1.0, 2.0, 3.0, 1.0, 2.0, 3.0], 
               [4.0, 5.0, 6.0, 4.0, 5.0, 6.0]])

M2 = np.array([[1.1, 2.1, 3.1, 1.2, 2.2, 3.2],
               [4.1, 5.1, 6.1., 4.2, 5.2, 6.2]])

I want to do a loop that can give the following arrays:

M3 = np.array([[1.1, 2.0, 3.0, 1.2, 2.0, 3.0], 
               [4.1, 5.0, 6.0, 4.2, 5.0, 6.0]])

M4 = np.array([[1.0, 2.1, 3.0, 1.0, 2.2, 3.0], 
               [4.0, 5.1, 6.0, 4.0, 5.2, 6.0]])

M5 = np.array([[1.0, 2.0, 3.1, 1.0, 2.0, 3.2], 
               [4.0, 5.0, 6.1, 4.0, 5.0, 6.2]])

1 Answer 1

1

You can use np.where:

selector = [1,0,0,1,0,0]
np.where(selector,M2,M1)
# array([[1.1, 2. , 3. , 1.2, 2. , 3. ],
#        [4.1, 5. , 6. , 4.2, 5. , 6. ]])
selector = [0,1,0,0,1,0]
np.where(selector,M2,M1)
# array([[1. , 2.1, 3. , 1. , 2.2, 3. ],
#        [4. , 5.1, 6. , 4. , 5.2, 6. ]])

etc.

Or in a loop:

M3,M4,M5 = (np.where(s,M2,M1) for s in np.tile(np.identity(3,bool), (1,2)))
M3
# array([[1.1, 2. , 3. , 1.2, 2. , 3. ],
#        [4.1, 5. , 6. , 4.2, 5. , 6. ]])
M4
# array([[1. , 2.1, 3. , 1. , 2.2, 3. ],
#        [4. , 5.1, 6. , 4. , 5.2, 6. ]])
M5
# array([[1. , 2. , 3.1, 1. , 2. , 3.2],
#        [4. , 5. , 6.1, 4. , 5. , 6.2]])

Alternatively, you can copy M1 and then slice in M2. This is more verbose but should be faster:

n = 3
Mj = []
for j in range(n):
    Mp = M1.copy()
    Mp[:,j::n] = M2[:,j::n]
    Mj.append(Mp)

M3,M4,M5 = Mj
Sign up to request clarification or add additional context in comments.

3 Comments

what if i have a very large number of columns and I want to specify that every 'n' columns pick one.
@ElenaPopa is the number of columns a mulitple of n?
@ElenaPopa never mind. I've added a method that works regardless. I'm pretty sure it will also be faster, so if your arrays are big I recommend it over the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.