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.
CodePudding user response:
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