pythonpandasdataframespydermagnitude

Pandas Dataframe - How do you check the sign of numeric values in a column, remove the sign if negative & create another column if this has happened?


Python 3.8, using Pandas.

I am trying to remove the sign from negative numbers in a pandas data frame column 'DATA' to just leave the magnitude, i.e. all values are positive. In essence, multiply the value in one column by -1, but only when it is negative. This is the easy bit. Then create a record in the dataframe that it has been inverted. So in this instance create another column called "Tubes Inverted"

 #Check sign and create a column recording if this has been inverted. 
            num = df['DATA']._get_numeric_data()
            if num < 0:
                df['Tubes Inverted'] = "Yes"
            else:
                df['Tubes Inverted'] = "No"
            num[num < 0] = num*-1

The issue here is that I am trying to determine the truth value of a series, which is ambiguous and cannot work so I tried:

            num = df['DATA']._get_numeric_data()
            for i in num:
                if i < 0:
                    df['Tubes Inverted'] = "Yes"
                else:
                    df['Tubes Inverted'] = "No"
            num[num < 0] = num*-1

But then I think that this is just the index position of the data it's testing, not the data itself.

There must be a more elegant & pythonic solution to this!


Solution

  • you have 2 requirements here, also you don't need loops here:

    First , create a conditional column using np.where after checking the condition:

    df['Tubes Inverted'] = np.where(df['DATA']<0,"Yes","No")
    

    Then using series.abs() you can convert to absolute value for the DATA column.

    df['DATA'] = df['DATA'].abs()