1

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!

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.