0

I would like to replace a specific value or values with another value.

Data

ID  Date    hi     hello
AA  Q4.2022 1      0
BB  Q4.2022 1      1
CC  Q4.2022 HI111  1    

Desired

ID  Date    hi     hello
AA  Q4.2022 1      0
BB  Q4.2022 1      1
CC  Q4.2022        1    

Doing

I have using this statement, however, this deletes the all the values

df['hi'] = df['hi'].str.replace('HI111','')

Any suggestion is appreciated.

2
  • 1
    it works as intended when I try it Commented Mar 1, 2022 at 1:36
  • it is deleting all the other values - the entire column is blank Commented Mar 1, 2022 at 1:40

1 Answer 1

1

Perhaps, the numbers are int types; then you could try to_numeric + isna and use it in mask:

df['hi'] = df['hi'].mask(pd.to_numeric(df['hi'], errors='coerce').isna(), '')

or if you want to change the type of the numbers to strings as well, you could use to_numeric + fillna + astype(str):

df['hi'] = (pd.to_numeric(df['hi'], errors='coerce').fillna('')
            .astype(str).str.split('.').str[0])

Output:

   ID     Date hi  hello
0  AA  Q4.2022  1      0
1  BB  Q4.2022  1      1
2  CC  Q4.2022         1
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.