Cast Value As Negative Float If There Is A "-" Sign At The End With Pandas
Within a dataframe I have a column called 'Val' where I have float values, but the negative values are represented by the '-' sign AT THE END! And therefore it is interpreted as ob
Solution 1:
You can use loc
to correct only entries ending with -
mask = df.Val.str.endswith('-')
df.loc[mask, 'Val'] = '-' + df.loc[mask, 'Val'].str[:-1]
and then convert to numeric dtype
df['Val'] = pd.to_numeric(df.Val, errors='coerce')
Final result
50.01873 -0.2496100.04252.0Name:Val,dtype:float64
Solution 2:
You can do with str.strip
, then using np.where
with str.endswith
s1=df.x.str.strip('+|-').astype('float')
np.where(df.x.str.endswith('-'),s1*-1,s1)
array([ 0. , -0.2, 100. , 2. ])
Post a Comment for "Cast Value As Negative Float If There Is A "-" Sign At The End With Pandas"