I have a dataframe filled with True and False values, and I’d like to get a dataframe from it with the True replaced with 1 and the False replaced with np.NaN. I’ve tried using dataframe.replace, but it gave a dataframe filled with all True. Is there a way to do it without using for loops and if’s?
Example, this is the dataframe I have, with T for True and F for False (not strings ‘T’ and ‘F’; sorry, could not figure out how to format a nicely spaced table in the wiki):
2008-01-02 16:00:00 T T F
2008-01-03 16:00:00 T T T
2008-01-04 16:00:00 T T F
2008-01-07 16:00:00 T T T
2008-01-08 16:00:00 T T F
This is what I would like to change it to:
2008-01-02 16:00:00 1 1 np.NaN
2008-01-03 16:00:00 1 1 1
2008-01-04 16:00:00 1 1 np.NaN
2008-01-07 16:00:00 1 1 1
2008-01-08 16:00:00 1 1 np.NaN
These are the lines I tried to replace the True and False, and got a dataframe filled with all True values:
df.replace(to_replace=True, value=1, inplace=True, method=None)
df.replace(to_replace=False, value=np.NAN, inplace=True, method=None)
When tried separately, the first line alone does not change anything; the second line converts all the values to True.
applymap()can be used to apply a function to every element of adataframeYou can also use a
dict:Addressing DSM’s comment from below. I misread the OP and assumed the datetime was an index. If it’s not an index this worked for me: