How to match True and False with “Yes” and “No” in a pandas data frame for dtype bool columns only?

I have a data frame pandas(v 0.20.3):

df = pd.DataFrame({'coname1': ['Apple','Yahoo'], 'coname2':['Apple', 'Google']})
df['eq'] = df.apply(lambda row: row['coname1'] == row['coname2'], axis=1).astype(bool)

   coname1 coname2     eq
0    Apple   Apple   True
1    Yahoo  Google  False

If I would like to replace True/Falsewith 'Yes'/'No', I could run this:

df.replace({
                True: 'Yes',
                False: 'No'
            })

   coname1 coname2   eq
0    Apple   Apple  Yes
1    Yahoo  Google   No

Which seems to be doing its job. However, if the data frame is only one row with a value 0/1in the column, it will also be replaced because it is treated as a logical one.

df1 = pd.DataFrame({'coname1': [1], 'coname2':['Google'], 'coname3':[777]})
df1['eq'] = True

   coname1 coname2  coname3    eq
0        1  Google      777  True

df1.replace({
                True: 'Yes',
                False: 'No'
            })

  coname1 coname2 coname3   eq
0     Yes  Google     777  Yes

I would like to display True/Falsein Yes/Nofor all the columns in the data frame that matter dtype bool.

How to report pandas, in order to run the True / False map for arbitrary rows only for columns with dtype boolno explicit column names, since I may not know them in advance

+4
3

dtypes, , , :

df = pd.DataFrame({'A': [0, 1], 'B': ['x', 'y'], 
                   'C': [True, False], 'D': [False, True]})

df
Out: 
   A  B      C      D
0  0  x   True  False
1  1  y  False   True

bool_cols = df.columns[df.dtypes == 'bool']

df[bool_cols] = df[bool_cols].replace({True: 'Yes', False: 'No'})

df
Out: 
   A  B    C    D
0  0  x  Yes   No
1  1  y   No  Yes

, :

for col in df.columns[df.dtypes == 'bool']:
    df[col] = df[col].map({True: 'Yes', False: 'No'})
+7

, , bool , applymap:

import pandas as pd

df1 = pd.DataFrame({'coname1': [1], 'coname2':['Google'], 'coname3':[777]})
df1['eq'] = True

def bool2yes(boolean):
    if isinstance(boolean, bool):
        if boolean == True:
            return "Yes"
        else:
            return "No"
    else:
        return boolean

>>> df1.applymap(bool2yes)
   coname1 coname2  coname3   eq
0        1  Google      777  Yes
+3

My take

cols = df.columns[df.dtypes.eq(bool)]
vals = np.column_stack([df[c].values for c in cols])

df[cols] = np.array(['No', 'Yes'])[vals.astype(int)]

df

   A  B    C    D
0  0  x  Yes   No
1  1  y   No  Yes
+2
source

Source: https://habr.com/ru/post/1681805/


All Articles