1

I've look at this answer: How can I selectively escape percent (%) in Python strings? and I believe my problem is different.

I'm trying to convert a percentage to decimal, but first I need to test if a percentage signs exists. My data is in a dataframe. My code is:

df[i]=df[i].map(lambda x: float(x.strip('%'))/100 if '%' in x)

This gives me SyntaxError: invalid syntax

Community
  • 1
  • 1
jason
  • 3,811
  • 18
  • 92
  • 147
  • Why do you need to check if the `%` exists? `strip` will still work if there is no `%`, it just won't do anything if there's nothing to strip. – BrenBarn Jun 29 '14 at 03:31
  • @brenbarn. I have other data that is not a percentage, so if i don't test, it will divide everything by `100` – jason Jun 29 '14 at 03:38

1 Answers1

2

It seems you need else in lambda like this

lambda x: float(x.strip('%'))/100 if '%' in x else x
furas
  • 134,197
  • 12
  • 106
  • 148
  • I think that worked. So it was not a `%` break after all? why do I need the `else x`? `lambda` must do something? – jason Jun 29 '14 at 03:43
  • It is syntax problem. There is no `result_if_true if condition`, there is only `result_if_true if condition else result_if_false` – furas Jun 29 '14 at 03:46