Filippo Sebastio
Filippo Sebastio

Reputation: 1112

Converting boolean to zero-or-one, for all elements in an array

I have the following datasets of boolean columns

            date     hr  energy
0     5-Feb-18  False   False
1    29-Jan-18  False   False
2     6-Dec-17   True   False
3    16-Nov-17  False   False
4    14-Nov-17   True    True
5    25-Oct-17  False   False
6    24-Oct-17  False   False
7     5-Oct-17  False   False
8     3-Oct-17  False   False
9    26-Sep-17  False   False
10   13-Sep-17   True   False
11    7-Sep-17  False   False
12   31-Aug-17  False   False

I want to multiply each boolean column by 1 to turn it into a dummy

I tried:

df = df.iloc[:, 1:]

for col in df:
    col = col*1

but the columns remain boolean, why?

Upvotes: 2

Views: 242

Answers (2)

Sreekiran A R
Sreekiran A R

Reputation: 3421

For future cases other than True or False, If you want to convert categorical into numerical you could always use the replace function.

    df.iloc[:,1:]=df.iloc[:,1:].replace({True:1,False:0})

Upvotes: 1

BENY
BENY

Reputation: 323326

Just using

df.iloc[:,1:]=df.iloc[:,1:].astype(int)
df
Out[477]: 
         date  hr  energy
0    5-Feb-18   0       0
1   29-Jan-18   0       0
2    6-Dec-17   1       0
3   16-Nov-17   0       0
4   14-Nov-17   1       1
5   25-Oct-17   0       0
6   24-Oct-17   0       0
7    5-Oct-17   0       0
8    3-Oct-17   0       0
9   26-Sep-17   0       0
10  13-Sep-17   1       0
11   7-Sep-17   0       0
12  31-Aug-17   0       0

Upvotes: 3

Related Questions