0

I am trying to multiply -1 to all credit charges while keeping debit charges the same using list comprehension but, the if function was ignored. I suspect there is a syntax error here if transactions['Transaction Type'] is "debit" but I cannot figure out why.

Here is the code

transactions['Value'] = [
    i if transactions['Transaction Type'] is "debit" 
    else i*-1 
    for i in transactions['Amount']
]

print(transactions.loc[:, ['Amount','Transaction Type','Value']])

The result contains all negative values on Value:

             Amount Transaction Type    Value
Date                                         
2018-12-06    19.57            debit   -19.57
2018-12-06    27.87            debit   -27.87
2018-12-06     6.25            debit    -6.25
2018-12-06    14.38            debit   -14.38
2018-12-06    15.60            debit   -15.60
...             ...              ...      ...
2019-11-30    10.59            debit   -10.59
2019-11-30    51.32            debit   -51.32
2019-11-30   634.51           credit  -634.51
2019-12-01  4432.00            debit -4432.00
2019-12-01     5.00            debit    -5.00
rcy222
  • 3
  • 2
  • this might have to do with spaces? try changing the condition to: `if "debit" in transactions['Transaction Type']` – Tomerikoo Dec 02 '19 at 20:57
  • Why do you want to use a list comprehension? I guess you can write this piece of code in 'classic' style in less than 2mins. Think about the poor guy who has to maintain the code after you left the company. IMHO there are places for list comprehension (creating simple lists), but it shouldn't complicate the code. Code should be easy to maintain, that means easy to understand. – Frieder Dec 02 '19 at 21:13

1 Answers1

1

There are two problems in the if transactions['Transaction Type'] is "debit" portion as you suspected.

First, using is checks if two objects are the same object, not if they are equal.

Second, transactions['Transaction Type'] is most likely a list (or at least list-like), based on the other info in your question. Even if you were using == like you should be, it would still be False, because a list will never be equal to a string.

Then, you're iterating the values in transactions['Values'], but only ever comparing to the transactions['Transaction Type'] entry (which again, is a list). You need to iterate both at the same time so that you're comparing the transaction type with the right amount:

transactions['Value'] = [
    i if j == "debit" else i * -1
    for i, j in zip(transactions['Amount'], transactions['Transaction Type'])
]
b_c
  • 1,202
  • 13
  • 24