0

I have a df, where in one column contains values in the form of strings which includes numbers & nan values. That column is represented in the form of string, where each values in the string seperated using :(colan)instead of , (comma)(see below column no n represeneted as cln)

index cl1   cl2    .... cln
0      1.1  6.4    .    '12.30 : 14.27 : nan : 15.87, nan .....'
1      2    5.3         '12.8 : 13.73 : nan : 15.87, 12.8 .....'
2      5    6.6
.     .     . 
.     .     .
.     .     .
.    
m     cl1m cl2m          '12.8 : 13.73 : nan : 15.87, 12.8 .....'

I want to replace : instead of comma using a single line of code using lambda fn.

df['cln'] = df['cln'].apply(lambda x : x.replace(':', ',') if x != np.nan)

But i received the following error

SyntaxError: invalid syntax

Even i tried the below code but it shows the same error

df['cln'] = df['cln'].apply(lambda x : x.replace(':', ',') if type(x) = str)
# since nan is float

i know how to use for loop and solve this problem, but i just want to know why it doesn't work using Lambda fn

Expecting pythonic answers for this problem

1
  • 2
    You need to have else clause to if. Commented Mar 23, 2020 at 12:21

1 Answer 1

3

You need an else:

df['cln'] = df['cln'].apply(lambda x : x.replace(':', ',') if x != np.nan else x)

Or better yet, just filter out the null:

df[df['cln'].notnull()].apply(lambda x: x.replace(':', ','))

Otherwise, you could see this result:

np.nan == np.nan
False
np.nan != np.nan
True
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.