Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a string prefix to non-missing dataframe values?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading