w3resource

NumPy: Create a new vector with 2 consecutive 0 between two values of a given vector


Insert zeros between elements in an array.

Write a NumPy program to create a new vector with 2 consecutive 0 between two values of a given vector.

Pictorial Presentation:

Python NumPy: Create a new vector with 2 consecutive 0 between two values of a given vector

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array 'nums' containing numbers from 1 to 8
nums = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# Displaying the original array 'nums'
print("Original array:")
print(nums)

# Variable 'p' set to 2
p = 2

# Creating a new array 'new_nums' of length len(nums) + (len(nums) - 1) * p filled with zeros
new_nums = np.zeros(len(nums) + (len(nums) - 1) * (p))

# Filling the 'new_nums' array with elements from 'nums' at intervals of (p + 1)
new_nums[::p + 1] = nums

# Displaying the new array 'new_nums'
print("\nNew array:")
print(new_nums)

Sample Output:

Original array:
[1 2 3 4 5 6 7 8]

New array:
[1. 0. 0. 2. 0. 0. 3. 0. 0. 4. 0. 0. 5. 0. 0. 6. 0. 0. 7. 0. 0. 8.]

Explanation:

In the above code -

nums = np.array([1,2,3,4,5,6,7,8]): Initializes a NumPy array nums with values 1 to 8.

p = 2: Sets the value of p to 2, meaning 2 zeros will be inserted between each element of the original array.

new_nums = np.zeros(len(nums) + (len(nums)-1)*(p)): This line creates a new NumPy array new_nums filled with zeros. The length of new_nums is calculated based on the length of the original array and the number of zeros to be inserted between each element.

new_nums[::p+1] = nums: This line assigns the elements of the original array nums to the corresponding positions in the new array new_nums, skipping p+1 indices for each assignment.

Python-Numpy Code Editor: