squeegene
squeegene

Reputation: 487

How to make number negative if other column meets some condition?

If I have several columns

Transaction Type    Amount
debit               1
credit              1

How do I iterate through columns such that the Amount becomes negative if the Transaction Type is debit?

Transaction Type    Amount
debit               -1
credit              1

Upvotes: 1

Views: 127

Answers (3)

louis_guitton
louis_guitton

Reputation: 5677

You want df.Amount[df['Transaction Type']=='debit'] = - df.Amount

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

(-1) ** True gives us -1, (-1) ** False gives us 1:

In [105]: df.Amount *= (-1) ** (df['Transaction Type'].eq('debit'))

In [106]: df
Out[106]:
  Transaction Type  Amount
0            debit      -1
1           credit       1

Upvotes: 3

BENY
BENY

Reputation: 323226

Using .loc

df.loc[df['TransactionType']=='debit','Amount']=-df.Amount
df
Out[376]: 
  TransactionType  Amount
0           debit      -1
1          credit       1

Upvotes: 3

Related Questions