Pandas select columns by regex and change their values by if, else

Viewed 179

I have Pandas data frame like this:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     0.10       0.0        0.21     0.0      0.03    0.10     0.04      0.0

How can I change it to the following:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     1          0           1       0        1       0        1          0

So, I want to select b* and c* columns and change any non-zero value into 1 and any zero value into 0. So, first selecting columns by regex then apply if-else rule there. It is also worth noting that all b*, c* columns are string (obj) types.

How can I do this?

2 Answers

Regex is not necessary, use str.startswith instead:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col] > 0).astype(int)
print(df)

Prints:

    a  b1  b2  b3  b4  c1  c2  c3  c4
0  a1   1   0   1   0   1   1   1   0

Edit: If your "numbers" are strings originally, you can do:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col].astype(float) > 0).astype(int)
# if you want keep them as strings after computation:
# df[filter_col] = (df[filter_col].astype(float) > 0).astype(int).astype(str)
print(df)

Another option is str.match:

mask = df.columns.str.match('^(b|c)')
df.loc[:, mask] = np.where(df.loc[:,mask].astype(float)==0, '0', '1')
Related