Normalize negative values in python

Viewed 66

I am trying to shift my negative values so that they become positive but in the way that will still somewhat preserve the data, so I know where the "true" positive values are. For example, if i have a table like this:

x     | 
______
1     | 
56    |
-34   |
34    |
-23   |
457   |

I can see that in column X, the absolute max negative value is -34, I want to add 34 to each number in that column X, so it becomes this:

x    |
_____
35   |
90   |
0    |
68   |
11   |
491  |

I made this work:

df = df-df.min()

But this takes the minimum of each column in dataframe.

How do I formulate a function that will pick max from the whole dataset (not each column) and apply it to all columns? So that most negative one from the whole dataset will become zero and all other numbers become positive.

1 Answers

Assuming all columns are numeric, the following should subtract the overall minimum value from all columns:

# Get the overall minimum value in the data frame
minimum = df.min(numeric_only=True).min()

# Subtract that minimum value from all values 
# in the data frame
df = df.transform(lambda x: x - minimum)

Or if you have non-numeric columns

# Transform only the numeric columns
df[["num_1", "num_2"]] = df[["num_1", "num_2"]].transform(lambda x: x - minimum)
Related