Andres
Andres

Reputation: 183

Append string to some dataframe rows with Pandas

This is my first question on stackoverflow! Please, be patient :)

I want to add a text to some rows in a DataFrame. The original dataframe looks like this:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'Name and rooms' : ['Excalibur: 1 room','John: 2 rooms','1 room','Lucas: 5 rooms','4 rooms','Jeremy: 1 room']})

In [3]: df
Out[3]: 
      Name and rooms
0  Excalibur: 1 room
1      John: 2 rooms
2             1 room
3     Lucas: 5 rooms
4            4 rooms
5     Jeremy: 1 room

As you see, there are some rows where the name is missing. I want to add some fixed string (like "Whatever: ", no matter what string) to the rows where no name exists (in this example, rows 2 and 4). The final dataset would look like this:

In [11]: df
Out[11]: 
      Name and rooms
0  Excalibur: 1 room
1      John: 2 rooms
2      Whatever: 1 room
3     Lucas: 5 rooms
4      Whatever: 4 rooms
5     Jeremy: 1 room

I'm new at pandas/python, so any help would be very appreciated.

Thanks!

Upvotes: 1

Views: 3850

Answers (1)

EdChum
EdChum

Reputation: 394071

Use the vectorised str method contains to create a boolean mask and use the negation operator ~, pass this to loc and prepend your string to the current value:

In [83]:

df.loc[~df['Name and rooms'].str.contains(':'),'Name and rooms'] = 'Whatever: ' + df['Name and rooms']
df
Out[83]:
      Name and rooms
0  Excalibur: 1 room
1      John: 2 rooms
2   Whatever: 1 room
3     Lucas: 5 rooms
4  Whatever: 4 rooms
5     Jeremy: 1 room

Upvotes: 2

Related Questions