0

I'm trying to iterate on a dataframe. I want to replace a few characters by anothers, unless the item I'm iterating is null/nan/NaN/etc.

For that I'm trying to use this line below:

lista['ultima_receita'] = lista['ultima_receita'].apply(lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False)

However it keeps getting me a invalid synthax error:

    lista['ultima_receita'] = lista['ultima_receita'].apply(lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False)
                                                                                                                                                     ^
SyntaxError: invalid syntax

I've tried everything I could and didn't find out the reason why the synthax is wrong. Can someone help?

1 Answer 1

3

Try making your question simpler. The lambda is indeed the issue, so this has nothing to do with pandas here.

>>> lambda rstr: float(rstr.replace('.','').replace(',','.')[3:]) if pd.isnull(rstr) == False
SyntaxError: invalid syntax  # At the end of 'False' above

or even simpler:

>>> lambda x: "foo" if "bar" == False
SyntaxError: invalid syntax

This is because python needs an else for the A if B else C construction. If you want to do a conditional modification you could make this else rstr, or use other pandas / numpy logic to do different logic.

>>> func = lambda x: "foo" if "bar" in x else x
>>> func("isobaric"), func("agnostic")
('foo', 'agnostic')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.