-1

I'm having a syntax error when applying the lambda function, however, I'm using the same lambda structure as in other functions. Is it an issue with the apply function on pandas?

for column in list2:
        print(column[-1])
        data[f'{column}'] = data[f'{column}'].apply(lambda x: str(x).replace('.','').replace('M','0000000') if (x[-1] == 'M'))
        data[f'{column}'] = data[f'{column}'].apply(lambda x: str(x).replace('.','').replace('B','0000000000') if (x[-1] == 'B'))
user15464793
  • 99
  • 2
  • 9
  • 1
    It looks like you're trying to use a conditional expression (A if B else C) and you omitted the `else` after the `if`. – khelwood Sep 08 '21 at 20:54
  • @khelwood I added an else pass statement as well, but got the same syntax error – user15464793 Sep 08 '21 at 20:56
  • It has to be a value expression – Barmar Sep 08 '21 at 20:56
  • It seems like you're tying to do something like [Convert the string 2.90K to 2900 or 5.2M to 5200000 in pandas dataframe](https://stackoverflow.com/q/39684548/15497888) I'd recommend adapting one of these approaches over a loop and apply with lambda. – Henry Ecker Sep 08 '21 at 20:57
  • `pass` is not an expression: it does not express any value. – khelwood Sep 08 '21 at 20:57
  • You **cannot** use a statement inside of a lambda expression, only expressions. If you want to, just use a regular function definition statement – juanpa.arrivillaga Sep 08 '21 at 21:11

1 Answers1

0

SOLVED:

for column in list2:
    print(column[-1])
    data[f'{column}'] = data[f'{column}'].apply(lambda x: (str(x).replace('.','').replace('M','0000000')) if str(x[-1]) == 'M' else x )
    data[f'{column}'] = data[f'{column}'].apply(lambda x: (str(x).replace('.','').replace('B','0000000000')) if str(x[-1]) == 'B' else x)
user15464793
  • 99
  • 2
  • 9