简体   繁体   中英

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.

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,

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]]

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]]

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]]

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

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