3

I am trying to find the proper python syntax to create a flag with a value of yes if columnx contains any of the following numbers: 1, 2, 3, 4, 5.

def create_flag(df):
    if df['columnx'] in (1,2,3,4,5):
        return df['flag']=='yes'

I get the following error.

TypeError: invalid type comparison

Is there an obvious mistake in my syntax?

1
  • Python is both case and space sensitive. The code you posted will raise a syntax error before it gets to type error. Commented Oct 31, 2018 at 6:36

2 Answers 2

2

Use np.where with pandas isin as:

df['flag'] = np.where(df['columnx'].isin([1,2,3,4,5]),'yes','no')
Sign up to request clarification or add additional context in comments.

2 Comments

TypeError: isin() takes 2 positional arguments but 4 were given is the error i get
@pynewbee can you please check the syntax inside isin whether you have given list as [1,2,3,4,5] or something else.
0

You have lot of problems in your code! i assume you want to try something like this

def create_flag(df):
    if df['columnx'] in [1,2,3,4,5]:
        df['flag']='yes'

x = {"columnx":2,'flag':None}

create_flag(x)
print(x["flag"])

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.