0

I have a data frame similar to this

name gender d1 d2  d3
dfd    M    F   F  F
adj    F    abc F  F
dfdf   F    F   df F
dfd    NA   F   F  dfd
daf    F    adf F  F

for column d1, d2, d3, I want to convert all non-F value (abc, df, adf, dfd, and many others) into T.

my current code is:

for item in d1, d2, d3:
    if item != F:
       return 'T'

This would work, but it runs really long. Is there a pandas command that does this directly?

2 Answers2

1

Use pd.where:

cols = ['d1', 'd2', 'd3']

df[cols] = df[cols].where(df[cols]=='F', 'T')
Michael Delgado
  • 13,789
  • 3
  • 29
  • 54
0

This will work:

df[['d1','d2','d3']]=df[df[['d1','d2','d3']].isin(['F'])][['d1','d2','d3']].fillna('T')
j__carlson
  • 1,346
  • 3
  • 12
  • 20