简体   繁体   English

python 中的条件字符串替换

[英]conditional string replace in python

I want to replace all "No" from a data frame col.我想替换数据框 col 中的所有“否”。 but if col consists for any other string like "No error" then it will remain as it is.但是如果 col 包含任何其他字符串,例如“No error”,那么它将保持原样。

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.我可以通过使用 np.where 获得结果,但我还有其他几个条件替换标准,其中“np.where”不起作用。 If I can make the above approach work it'll be great.如果我能让上述方法奏效,那就太好了。 Any help is greatly appreciated.任何帮助是极大的赞赏。

Looks like you need np.where看起来你需要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: Output:

                 text
0  Data not available
1            No Error

You can also use, Series.replace您也可以使用Series.replace

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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