Home > other >  In python numpy, how to replace some rows in array A with array B if we know the index
In python numpy, how to replace some rows in array A with array B if we know the index

Time:01-27

In python numpy, how to replace some rows in array A with array B if we know the index.

For example

we have

a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,10],[1000, 1000]])
index = [0,2]

I want to change a to

a = np.array([[10,10],[3,4],[1000,1000]])

I have considered the funtion np.where but it need to create the bool condition, not very convenient,

CodePudding user response:

I would do it following way

import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,10],[1000, 1000]])
index = [0,2]
a[index] = b
print(a)

gives output

[[  10   10]
 [   3    4]
 [1000 1000]]

CodePudding user response:

You can use :

a[index] = b

For example :

import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
b = np.array([[10,10],[1000, 1000]])
index = [0,2]
a[index] = b
print(a)

Result :

[[  10   10]
 [   3    4]
 [1000 1000]]

CodePudding user response:

In Python's NumPy library, you can use the numpy.put() method to replace some rows in array A with array B if you know the index. Here's an example:

import numpy as np

# Initialize array A
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Initialize array B
B = np.array([[10, 20, 30], [40, 50, 60]])

# Indices of the rows to be replaced in array A
indices = [0, 1]

# Replace rows in array A with rows in array B
np.put(A, indices, B)
print(A)

In this example, the first two rows in array A are replaced with the first two rows in array B, so the output will be

[[10 20 30]
 [40 50 60]
 [ 7  8  9]]

CodePudding user response:

Simply a[indices] = b or if you want to be more fancy np.put(a, indices, b)

  • Related