Question:
How to replace a value in certain columns of a 3d Numpy array?

You can use array indexing and assignment in a 3D NumPy array to change the values in specific columns. Try using the following line of code:


Solution:


import numpy as np

data = np.array([

    [[10, 10, 10], [0, 10, 10], [0, 10, 0]],

    [[20, 0, 20], [20, 20, 0], [0, 20, 20]],

    [[0, 30, 30], [30, 0, 30], [0, 30, 30]],

])


columns_to_replace = [0, 1]

value_to_replace = 1000


# Create a boolean mask for the zeros

mask = data[:, columns_to_replace, :] == 0


# Use the mask to replace the zeros with the desired value

data[:, columns_to_replace, :][mask] = value_to_replace


print(data)


The result you might get is as follows:

[[[  10   10   10]

[1000   10   10]

[   0   10    0]]


[[  20 1000   20]

[  20   20 1000]

[   0   20   20]]


[[1000   30   30]

[  30 1000   30]

[   0   30   30]]]



Suggested blogs:

>Testing react components using Hooks and Mocks

>Use Firebase Realtime Database with ASP.NET MVC App

>Use of Singletons in .NET Core in AWS Lambda

>What are common syntax errors and exceptions in Python

>What are the steps to fix error while downloading PDF file- Python

>How to do PHP Decryption from Node.js Encryption?

>How to do PHP gd Installation on Ubuntu?

>How to do Web Scraping with Python?

>How to do wild grouping of friends in Python?


Ritu Singh

Ritu Singh

Submit
0 Answers