Samulafish :
I have code as below:
s = pd.Series(['$2.75', np.nan, 4.150000, 25.00, '$4.50','k876','g67.3'])
strs = s.astype(str).str.replace("$", "").replace("k", "").replace("g", "")
#strs = s.astype(str).str.replace({'\$': '', ',': ''}, regex=True)
res = pd.to_numeric(strs, errors='coerce').fillna(0)
print(res)
I suppose output should be:
0 2.75
1 0.00
2 4.15
3 25.00
4 4.50
5 876
6 67.3
But instead, row 5 and 6 actually result is zero.
Please help point out the mistake. I appreciate any suggestions.
moys :
Use regex=True
in your replace
codes, like below
s = pd.Series(['$2.75', np.nan, 4.150000, 25.00, '$4.50','k876','g67.3'])
strs = s.astype(str).str.replace("$", "", regex=True).replace("k", "", regex=True).replace("g", "", regex=True)
res = pd.to_numeric(strs, errors='coerce').fillna(0)
print(res)
Output
0 2.75
1 0.00
2 4.15
3 25.00
4 4.50
5 876.00
6 67.30
dtype: float64