coder_bg
coder_bg

Reputation: 370

How to create another column in pandas based on a condition?

I have two columns - Punchout and Contract. I want a catalog flag column where it is FALSE if Punchout and Contract both are NAN otherwise it is TRUE. I wrote the following piece of code:

req_line['Catalog_Flag'] = np.where((req_line['Contract']) & (req_line['Punchout']) = '[]',False,True)

but the error it throws is : SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Is there any other way also? Please help!

SAMPLE DATA

Contract | Punchout | Flag
NaN      | NaN      | False
NaN      | Computer Information | True
Non-CLM0_Cat_01 | NaN | True

Upvotes: 1

Views: 105

Answers (2)

jezrael
jezrael

Reputation: 863541

Here np.where is not necessary, just use ~ for invert mask with Series.isna:

req_line['Catalog_Flag'] = ~(req_line['Contract'].isna() & req_line['Punchout'].isna())

Working like test if no missing values with | for bitwise OR by Series.notna:

req_line['Catalog_Flag'] = req_line['Contract'].notna() | req_line['Punchout'].notna()

print (req_line)
          Contract              Punchout   Flag  Catalog_Flag
0              NaN                   NaN  False         False
1              NaN  Computer Information   True          True
2  Non-CLM0_Cat_01                   NaN   True          True

Upvotes: 3

Mayank Porwal
Mayank Porwal

Reputation: 34086

Use Series.isna for identifying nan:

req_line['Catalog_Flag'] = np.where(req_line['Contract'].isna() & req_line['Punchout'].isna(), False, True)

Upvotes: 2

Related Questions