1

I am trying to create a new variable based off of an existing variable in my df. I have run into this error before and I would like to know what I am doing wrong.

Code:

def DEMO2(a):
    if a['DEMO']=='02-05C':
       return 'P 02-11'
    elif a['DEMO']=='65+M':
       return 'P 55-99'

merge_df['DEMO2']=merge_df.apply('DEMO2', axis=1)

TypeError: ("'str' object is not callable", 'occurred at index 0')

I feel like there is an obvious answer that I am missing...

1
  • 1
    I don't know Pandas, but do you actually want quotes around DEMO2? You want to pass the function itself don't you? Not just it's name? Commented Nov 9, 2017 at 15:44

2 Answers 2

2

You do not need the DEMO2 function even .

merge_df['DEMO2']=merge_df.DEMO.replace({'02-05C':'P 02-11','65+M':'P 55-99'})
Sign up to request clarification or add additional context in comments.

5 Comments

This is much quicker than using apply. Thank you.
@nakedbird226 if it is help you , can you consider accept and upvote ?
merge_df.replace({'DEMO': {'02-05C':'P 02-11','65+M':'P 55-99'}}) will also work.
@piRSquared this even better , will fill the none match one to NaN :-)
@nakedbird226 please using piR's answer :-)
0

Well you're getting that error because of this

merge_df['DEMO2']=merge_df.apply('DEMO2', axis=1)

Should (probably) be this:

merge_df['DEMO2']=merge_df.apply(DEMO2, axis=1)

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.