beginner
beginner

Reputation: 41

add prefixes in pandas df column

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'])

Upvotes: 0

Views: 193

Answers (4)

mozway
mozway

Reputation: 262149

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

Upvotes: 0

user17242583
user17242583

Reputation:

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

Upvotes: 1

Rabinzel
Rabinzel

Reputation: 7923

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

Upvotes: 0

Z Li
Z Li

Reputation: 4318

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

Upvotes: 0

Related Questions