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

Time:06-09

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?

CodePudding user response:

You can also use .applymap():

df.applymap(lambda x: ' '   str(x) if pd.notna(x) else x)

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

CodePudding user response:

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
  • Related