w3resource

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

NumPy: Array Object Exercise-185 with Solution

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:

import numpy as np
nums = np.array([1,2,3,4,5,6,7,8])
print("Original array:")
print(nums)
p = 2
new_nums = np.zeros(len(nums) + (len(nums)-1)*(p))
new_nums[::p+1] = 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.]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a NumPy program to create an array using generator function that generates 15 integers.
Next: Write a Numpy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2).

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}