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

Mutiplying dataframe by -1 loses data

I have an issue and I have no idea what is causing it.. I have a very very simply dataframe which looks like the following;

            A   B
01/01/2022 -34 -102.34
02/01/2022 -4  -89.23
03/01/2022 -78 -43.2
.
.
.
31/12/2022 -32 -34.21

I simply need to convert this dataframe to positive numbers.
When I do this with a simple;


df = df * -1

A column multiples but the B column loses its’ data to the following;

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


            A   B
01/01/2022 34 
02/01/2022 4  
03/01/2022 78 
.
.
.
31/12/2022 32 

I assume this is something to do with interger vs float64 but just can’t crack it.

Any help much appreciated!

>Solution :

You likely have strings in your data, multiplying a string by an integer less than 1 converts to empty string:

df = pd.DataFrame({'A': [0,1,2], 'B': [0,'1',2]})
df*-1

output:

   A   B
0  0   0
1 -1    
2 -2  -2

Workaround: convert to_numeric:

df.apply(pd.to_numeric, errors='coerce')*-1

# or
# df.astype(float)*-1

output:

   A  B
0  0  0
1 -1 -1
2 -2 -2
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