Hrishikesh
Hrishikesh

Reputation: 47

How to return 'negative' of a value in pandas dataframe?

In pandas, is there any function that returns the negative of the values in a column?

Upvotes: 1

Views: 3686

Answers (2)

Pawel Wisniewski
Pawel Wisniewski

Reputation: 440

You could use lambda function and apply. For example if I want negative values from column "value" I write something like this:

import pandas as pn
file_name = './exmp.txt'
names = ['class', 'value']
df = pn.read_csv(file_name, sep=': ', names=names, engine='python')
f = lambda x: -x
df['value'].apply(f)

Update

BrenBarn answer is much better, just add - before column name so for my example it would be:

import pandas as pn
file_name = './exmp.txt'
names = ['class', 'value']
df = pn.read_csv(file_name, sep=': ', names=names, engine='python')
-df['value']

It's much easier.

Upvotes: -1

BrenBarn
BrenBarn

Reputation: 251383

Just use the negative sign on the column directly. For instance, if your DataFrame has a column "A", then -df["A"] gives the negatives of those values.

Upvotes: 6

Related Questions