简体   繁体   中英

conditional string replace in python

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.

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

You can also use, Series.replace

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM