Is there a way to apply a function to multiple columns in a Pandas dataframe without a loop? For example, give this dataframe:
df = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9,10],
'val1': [2,2,np.nan,np.nan,4,1,np.nan,np.nan,np.nan,2],
'val2': [7,0.2,5,8,np.nan,1,0,np.nan,1,1],
})
display(df)
If I want to operate on both val1 and val2 columns, I can do the following. Is there a one-liner to replace the for-loop?
f = lambda x: 'ERR' if x < 5 else x
cols = ['val1', 'val2']
for c in cols:
df[c] = df[c].apply(f)
display(df)

