Search code examples
pythonpandasmultiplication

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;


            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