0

I want to replace all "No" from a data frame col. but if col consists for any other string like "No error" then it will remain as it is.

test = ["No","No Error"]
data = pd.DataFrame(test, columns=["text"])
for i in range(len(data["text"])):
    if len(data["text"][i]) == 2:
       data["text"][i] = data["text"][i]).str.replace("No", "Data not available", regex=True)
    else:
       pass
print(data)

I'm getting an error while running the code. I'm able to get the result by using np.where but I've had several other criteria for conditional replace where "np.where" won't work. If I can make the above approach work it'll be great. Any help is greatly appreciated.

1
  • 1
    That's because you only replace "No" in cells which contain a string that is exactly 2 characters long. Remove this condition and it works. Commented Aug 20, 2020 at 8:15

2 Answers 2

2

Looks like you need np.where

Ex:

test = ["No","No Error"]
data = pd.DataFrame(test, columns=["text"])
data['text'] = np.where(data['text'] == 'No', "Data not available", data['text'])
# OR data.text[data.text=='No'] = "Data not available" 
print(data)

Output:

                 text
0  Data not available
1            No Error
Sign up to request clarification or add additional context in comments.

1 Comment

Please accept(tick symbol) any one of the ans that helped you. Thanks
0

You can also use, Series.replace

data.text.replace({"No":"Data not available"})

0    Data not available
1              No Error
Name: text, dtype: object

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.