Replace a string value with another string in a column in pandas

Souvik Ray Source

I have a csv file which contains date, location and health status.

Date         Location            Health
2018-02-11   DELHI               OK
2018-02-11   MUMBAI              not responding
2018-02-11   KOLKATA             ok
2018-02-11   PUNE                ok
2018-02-11   CHENNAI             not responding
2018-02-11   NOIDA               OK
2018-02-11   GURGAON             not responding
2018-02-11   CHANDIGARH          ok

I want the strings ok in the Health column to be capitalized but as you can see, there are certain lowercase representations as well.How do I ensure the lowercase string ok is changed to upercase string OK?

I have used this function below

df = pd.read_csv("metrics.csv", parse_dates=["date"])
df['Health'].replace("ok", "OK", inplace=True)

But it still shows the lowercase ok.What am I doing wrong?

python-3.xpandas

Answers

answered 5 months ago youssef mhiri #1

Create a function that replace ok with OK

def replaceword(ok):
    if ok in 'ok':
        ok = 'OK'
        return ok
    else: 
        return ok

then use apply

df['Health'] = df['Health'].apply(replaceword)

comments powered by Disqus