2

I have a data frame with a variety of string values. For a given column, if there is any string entered, I would like to replace it with the same value (say 'fruit').

Example:

data = {'item_name': ['apple', 'banana', 'cherry', 'pineapple', 'apple pie', 'banana split', 'hafts to chos', 'lov_frutz', 'I always pick apples', None, None, None]}
df = pd.DataFrame(data)

Result I want:

item_name
'fruit'
'fruit'
'fruit'
'fruit'
'fruit'
'fruit'
'fruit'
'fruit'
'fruit'
nan
nan
nan

response = 'fruit'

I have tried using regex but don't seem to understand it correctly, so tried:

df[col] = df[col].replace(to_replace=r'\w\b', value = response, regex = True)
3
  • 2
    Try df.loc[df["item_name"].notna(), "item_name"] = "fruit". Commented Jul 15 at 17:24
  • 1
    Or df['item_name'][df['item_name'].notna()] = "fruit" Commented Jul 15 at 17:25
  • Should present be fruit? Commented Jul 15 at 20:01

1 Answer 1

4

Another possible solution, which uses where and isnull as its condition:

df.where(df.isnull(), "Fruit")

Output:

   item_name
0      Fruit
1      Fruit
2      Fruit
3      Fruit
4      Fruit
5      Fruit
6      Fruit
7      Fruit
8      Fruit
9       None
10      None
11      None
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.