0

The data looks like the below

Code  Col1  Col2   col3   col4  col5 col6    Col7  Col8
0    A      nan     nan   False  c    12     True   8
1    B      1       Nan   True   ab    1     True   9
2    C      Nan     5     True   rr    89.7  False  78.8
3    D      34.4    0     True   tr    123   True   90.3

I have more than 1 column having true/false data, the column will not always be in the same location and their number could defer, i want to replace the True anf False text with 1 or 0 numbers.

import pandas as pd
import datetime

# Create a dataframe
df = pd.read_excel(r'path.xls', sheet_name='mydata')
#print(df)

def foo_bar(x):
    if x == 'True':
        return x.replace('True', '1')

    if x == 'False':
        return x.replace('False', '0')

df.applymap(foo_bar)

for v in df['col 7']:
    print(v)

The print is showing :

True
True
False
True
1.0

the values are not being changed to True and False as expected

sara
  • 109
  • 1
  • 7
  • I think need [this](https://stackoverflow.com/a/65395517/2901002) – jezrael Dec 17 '21 at 13:58
  • @jezrael That will not work in that question all the data is True or False, mine can have empty cell, text or numbers. – sara Dec 17 '21 at 14:09
  • hmmm, do you try `replace` like mentioned in comment above? – jezrael Dec 17 '21 at 14:10
  • @jezrael I have and it gave me the following bug: 1 1 0 1 1.0 so even though i have 4 rows i'm still getting an additional 1.0 when i print for v in df['col 7']: print(v) it should be 1 1 0 1 – sara Dec 17 '21 at 14:11
  • For me working very well. There is not `True, False` and `1.0` value together? – jezrael Dec 17 '21 at 14:14
  • Fixed my file had a trailing data in that column for some reason so worked well when i copied only the table in question, thank you for your assistance :) – sara Dec 17 '21 at 14:18

0 Answers0