1

I try to initialize a Boolean array with False using np.empty,

init_arr = empty(5)
init_arr.fill(False)

but I got

array([0., 0., 0., 0., 0.])

then I create a pd.Series,

dummy_ser = pd.Series(data=init_arr)

which makes it

0       0
1       0
2       0
3       0
4       0

I tried to initialize a boolean series with various length with False as its initialized values. I am wondering whats the best way to do this.

I am using Python 3.5.2 and Numpy 1.15.4.

daiyue
  • 7,196
  • 25
  • 82
  • 149

3 Answers3

3

This is because the empty() function creates an array of floats:

In [14]: np.empty(5).dtype
Out[14]: dtype('float64')

There are many ways to solve this, supplying dtype=bool to empty() being one of them.

But I would create an array of False like this:

In [17]: np.full(5, False)
Out[17]: array([False, False, False, False, False], dtype=bool)
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
1

you could do :

np.zeros(5).astype(bool)
Ayoub ZAROU
  • 2,387
  • 6
  • 20
1

This will work:

>>> import numpy as np
>>> np.broadcast_to(False, (2, 2))
array([[ False,  False],
   [ False,  False]], dtype=bool)
Aravind
  • 534
  • 1
  • 6
  • 18