2

I am trying to apply lambda with if-else condition on a pandas df df looks like following:

col1 col2 col3 col4 <---column names
None None None col4 <---column values in str
col1 None None None
None col2 None None



df_twitter_archive_master[['col1','col2','col3','col4']].apply(lambda x: x=0 if x=='None' else x=1)

basically, it should replace 'None' value with 0 and else with 1 but I keep getting this error

df_twitter_archive_master[['col1','col2','col3','col4']].apply(lambda x: x=0 if x=='None' else x=1)

SyntaxError: invalid syntax

^ is under x=1

what am i doing wrong? ?

3
  • Can you post a sample dataframe with expected outputs? Commented Feb 16, 2018 at 3:51
  • ok just updated Commented Feb 16, 2018 at 3:54
  • 1
    While the rest of the answers get you the result, your problem came from the syntax x=0 and x=1. Within your lambda you shouldn't be assigning values. Just lambda x: 0 if x == 'None' else 1 will suffice. Commented Feb 16, 2018 at 4:08

2 Answers 2

6

IIUC

df.replace('None',np.nan).notnull().astype(int)
Out[31]: 
   col1  col2  col3  col4
0     0     0     0     1
1     1     0     0     0
2     0     1     0     0

Base on your lambda method

df.applymap(lambda x: 0 if x=='None' else 1)
Out[33]: 
   col1  col2  col3  col4
0     0     0     0     1
1     1     0     0     0
2     0     1     0     0
Sign up to request clarification or add additional context in comments.

4 Comments

what is difference between .apply and .applymap ??
i see, i just tested with 'else 1' it works, but when I remove else 1, it got same syntax error?
@ikel DataFrame.apply passes each column (default, axis=0) or row (axis=1) to the provided function. applymap operates on the individual elements within the rows and columns. Series.apply operates on the elements of the series. Series.map and Series.apply are subtly different in the general case, but are effective the same when passed a callable function.
5

Let's try:

(df != 'None').astype(int)

Output:

   col1  col2  col3  col4
0     0     0     0     1
1     1     0     0     0
2     0     1     0     0

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.