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]
Asked
Active
Viewed 41 times
0
-
You combine arrays made with `np.zeros` and `np.ones`. – hpaulj May 29 '22 at 15:40
3 Answers
1
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])
And more generally, see here: Interweaving two numpy arrays.

EliadL
- 6,230
- 2
- 26
- 43
0
Create an array of zeros and set every other element to one:
a = np.zeros(1000)
a[1::2] = 1

Nils Werner
- 34,832
- 7
- 76
- 98
-1
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

pandamoniark
- 21
- 1
- 4
-
1While there exists no single function to do this, a for loop is not the right answer. – Nils Werner Jun 01 '22 at 08:58