Convert multiple boolean columns whose names begin with the string `abc_` at once to an integer dtype

I need to have 1 and 0 instead of True and False in the pandas data frame only for columns starting with abc_. Is there a better way to do this other than my loop:

for col in df:
  if col[:4] =='abc_':
     df[col] = df[col].astype(int) 
+4
source share
3 answers

You can do this with filterand on the spot update.

df.update(df.filter(regex='^abc_').astype(int))
+5
source

Option 1: column conversion all boolean ( dtype == 'bool')

df.loc[:, df.dtypes.eq('bool')] = df.loc[:, df.dtypes.eq('bool')].astype(np.int8)

Option 2: if you want to convert only those logical columns that start with abc_:

col_mask = df.dtypes.eq('bool') & df.columns.str.contains('^abc_')
df.loc[:, col_mask] = df.loc[:, col_mask].astype(np.int8)

Option 3: Convert by Column Names Only

df.loc[:, df.columns.str.match(r'^abc_.*$')] = \
    df.filter(regex=r'^abc_').astype(np.int8)
+5
source

Using str.contains

df.loc[:,df.columns.str.contains('abc_')]=df.loc[:,df.columns.str.contains('abc_')].astype(int)
+4
source

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


All Articles