mlenthusiast
mlenthusiast

Reputation: 1194

Converting true/false to 0/1 boolean in a mixed dataframe

I have a dataframe with mixed data types. I want to create a function that goes through all the columns and converts any columns containing True/False to int32 type 0/1. I tried a lambda function below, where d is my dataframe:

f = lambda x: 1 if x==True else 0
d.applymap(f)

This doesn't work, it converts all my non boolean columns to 0/1 as well. Is there a good way to go through the dataframe and leave everything everything untouched except the boolean columns and convert them to 0's and 1's? Any help is appreciated!

Upvotes: 1

Views: 2958

Answers (3)

Nev1111
Nev1111

Reputation: 1049

If you have a dataframe df, try:

df_1=df.applymap(lambda x: int(x) if type(x)==bool else x)

Upvotes: 0

Vaishali
Vaishali

Reputation: 38415

You can select the columns using loc and change data type.

df = pd.DataFrame({'col1':np.random.randn(2), 'col2':[True, False], 'col3':[False, True]})

df.loc[:, df.dtypes == bool] = df.astype(int)



    col1      col2  col3
0   0.999358    1   0
1   0.795179    0   1

Upvotes: 2

cs95
cs95

Reputation: 402303

Let's modify your lambda to use an isinstance check:

df.applymap(lambda x: int(x) if isinstance(x, bool) else x)

Only values of type bool will be converted to int, everything else remains the same.


As a better solution, if the column types are scalar (and not "mixed" as I originally assumed given your question), you can instead use

u = df.select_dtypes(bool)
df[u.columns] = u.astype(int)

Upvotes: 2

Related Questions