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.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to insert two zeros between each element of a 1D array using np.insert in a loop-free manner.
  • Create a function that interleaves an array with a specified filler value and returns the new array.
  • Implement a solution that uses np.reshape and np.hstack to achieve the insertion of zeros between elements.
  • Test the function on arrays of various lengths to verify that the inserted zeros are correctly positioned.

Go to:


PREV : Create array using generator function.
NEXT : Multiply arrays of compatible dimensions.


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.