NumPy: Transform a given array
NumPy: Basic Exercise-51 with Solution
Write a NumPy program to create a new array of given shape (5,6) and type, filled with zeros.
Change the said array in the following format:
Given array:
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
New array:
[[3 0 3 0 3 0]
[7 0 7 0 7 0]
[3 0 3 0 3 0]
[7 0 7 0 7 0]
[3 0 3 0 3 0]]
Sample Solution:
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'nums' with shape (5, 6) filled with zeros of integer type
nums = np.zeros(shape=(5, 6), dtype='int')
# Printing a message indicating the original array
print("Original array:")
print(nums)
# Assigning value 3 to every alternate row and column starting from index 0
nums[::2, ::2] = 3
# Assigning value 7 to every alternate row starting from index 1 and every column starting from index 0
nums[1::2, ::2] = 7
# Printing the updated array after assigning values 3 and 7
print("\nNew array:")
print(nums)
Sample Output:
Original array: [[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]] New array: [[3 0 3 0 3 0] [7 0 7 0 7 0] [3 0 3 0 3 0] [7 0 7 0 7 0] [3 0 3 0 3 0]]
Explanation:
In the above code –
np.zeros(shape=(5, 6), dtype='int') creates a 5x6 2D array filled with zeros of integer type and stores in the variable ‘nums’
nums[::2, ::2] = 3: This line sets every second element in every second row, starting from the first row (0-th index), to the value 3.
nums[1::2, ::2] = 7: This line sets every second element in every second row, starting from the second row (1-st index), to the value 7.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy program to create a 4x4 array with random values, now create a new array from the said array swapping first and last rows.
Next: NumPy program to sort a given array by row and column in ascending order.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics