Example dataframe:
df = pd.DataFrame(dict(age=[5, 6, np.NaN], born=[pd.NaT, pd.Timestamp('1939-05-27'), pd.Timestamp('1940-04-25')], name=['Alfred', 'Batman', ''], toy=[None, 'Batmobile', 'Joker']))
I can detect non-missing values:
df.notna()
Let’s say I want to add ‘+’ as the string prefix to all non-missing values:
age born name toy
0 +5.0 NaT +Alfred None
1 +6.0 +1939-05-27 +Batman +Batmobile
2 NaN +1940-04-25 + +Joker
How can I use the returned boolean (dataframe) values to add a string prefix to every non-missing value?
>Solution :
What about:
df.mask(df.notna(), '+'+df.astype(str))
output:
age born name toy
0 +5.0 NaT +Alfred None
1 +6.0 +1939-05-27 +Batman +Batmobile
2 NaN +1940-04-25 + +Joker