Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert in python negative value objects in dataframe to float

may be someone can help me. Would like to create function to convert objects to float. Tried to find some solution, but always get some errors:

# sample dataframe
d = {'price':['−$13.79', '−$ 13234.79', '$ 132834.79', 'R$ 75.900,00', 'R$ 69.375,12', '- $ 2344.92']}
df = pd.DataFrame(data=d)

I tried this code, first wanted just to find solution.

df['price'] = (df.price.str.replace("−$", "-").str.replace(r'\w+\$\s+', '').str.replace('.', '')\
                   .str.replace(',', '').astype(float)) / 100

So idea was to convert -$ to – (for negative values). Then $ to ”.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But as a result I get:

ValueError: could not convert string to float: ‘−$1379’

>Solution :

You can extract the numbers on one side, and identify whether there is a minus in the other side, then combine:

factor = np.where(df['price'].str.match(r'[−-]'), -1, 1)/100
out = (pd.to_numeric(df['price'].str.replace(r'\D', '', regex=True), errors='coerce')
         .mul(factor)
       )

output:

0       -13.79
1    -13234.79
2    132834.79
3     75900.00
4     69375.12
5     -2344.92
Name: price, dtype: float64
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading