Home > Software engineering >  Vector generation using numpy in Python
Vector generation using numpy in Python

Time:05-30

how to create a vector with numpy array with alternate 0 and 1 for desired number of rows vectors of zeros or ones can be created with np.zeros(n) or np.ones(n). Is there any way to create vector of alternate zeros and ones like [0,1,0,1,0,1]

CodePudding user response:

To my knowledge, there is no function similar to np.zeros or np.ones which allows you to directly do that. A simple way to create such an array is to first create an array of the final size using np.zeros(2n) (assuming you want n zeros and n ones), and then replacing half of the 0 values by 1:

import numpy as np
n = 100
a = np.zeros(2*n)
for i in range(n):
    a[2*i 1] = 1

CodePudding user response:

Using np.tile:

def zeros_and_ones(n):
    repeats = (n   1) // 2
    return np.tile([0, 1], repeats)[:n]

zeros_and_ones(7)
# array([0, 1, 0, 1, 0, 1, 0])
  • Related