Home > Net >  How to add prefix to values in one column if not null using pandas
How to add prefix to values in one column if not null using pandas

Time:04-28

I have a data frame in which I need to add prefix to rows from one of the columns if it's not null

   Name  marks
0   Tom     99
1  Jack     98
2  Nan     95
3  juli     90

how can I add the prefix= "/new/" to the column Name if not null? so the New df will look like the following:

   Name       marks
0  /new/Tom    99
1  /new/ Jack  98
2  Nan         95
3  /new/juli   90

CodePudding user response:

like this I think

df['Name']=np.where(df['marks'].notna(),df['Name'] '/new/',df['Name'])

CodePudding user response:

add() works out of box

df['Name'] = df['Name'].add('/new/')

If it is string type Nan, you can use mask or np.where

df['Name'] = df['Name'].mask(df['Name'].ne('Nan'), df['Name'].add('/new/'))

# or

df1['Name'] = np.where(df1['Name'].ne('Nan'), df1['Name'].add('/new/'), df1['Name'])
  • Related