Home > other >  add prefixes in pandas df column
add prefixes in pandas df column

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

I want to add this text-to-add = "https://en.wikipedia.org/wiki/" to the column Name if not null? so the New df will look like the following:

  Name                                  marks
0  https://en.wikipedia.org/wiki/Tom    99
1  https://en.wikipedia.org/wiki/Jack    98
2  Nan                                   95
3  https://en.wikipedia.org/wiki/juli    90

I tried this solution

df['Name']=np.where(df['Name'].notna(),'https://en.wikipedia.org/wiki/'  df['Name'],df['Name'])

CodePudding user response:

Just add the text as you might normally do. Pandas automatically ignore NaNs when doing string processing:

text_to_add = "https://en.wikipedia.org/wiki/"
df["Name"] = text_to_add   df["Name"]

Output:

>>> df
                                 Name  marks
0   https://en.wikipedia.org/wiki/Tom     99
1  https://en.wikipedia.org/wiki/Jack     98
2                                 NaN     95
3  https://en.wikipedia.org/wiki/juli     90

CodePudding user response:

text_to_add = "https://en.wikipedia.org/wiki/"
df = pd.DataFrame({'name':['A','B', np.nan], 'marks':[1,2,3]})
df.loc[df['name'].notna(), 'name'] = text_to_add   df.loc[df['name'].notna(), 'name'].str[:]
    name                            marks
0   https://en.wikipedia.org/wiki/A 1
1   https://en.wikipedia.org/wiki/B 2
2   NaN                             3

CodePudding user response:

Here is one solution for it:

text_to_add = "https://en.wikipedia.org/wiki/"

df.loc[df["Name"].notna(), "Name"] = df.loc[df["Name"].notna(), "Name"].map(
    lambda x: "".join([text_to_add, x])
)

print(df)

    Name                                marks
0    https://en.wikipedia.org/wiki/Tom  99
1   https://en.wikipedia.org/wiki/Jack  98
2                                  NaN  95
3   https://en.wikipedia.org/wiki/juli  90

CodePudding user response:

If you really have NaNs, no need to test anything, just do:

text = "https://en.wikipedia.org/wiki/"

df['Name'] = text df['Name']

Output:

Name  marks
0   https://en.wikipedia.org/wiki/Tom     99
1  https://en.wikipedia.org/wiki/Jack     98
2                                 NaN     95
3  https://en.wikipedia.org/wiki/juli     90
  • Related