[英]How to create another column in pandas based on a condition?
我有两列 - Punchout 和 Contract。 我想要一个目录标志列,如果 Punchout 和 Contract 都是 NAN,则它是 FALSE,否则它是 TRUE。 我写了以下一段代码:
req_line['Catalog_Flag'] = np.where((req_line['Contract']) & (req_line['Punchout']) = '[]',False,True)
但它抛出的错误是: SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
还有其他方法吗? 请帮忙!
样本数据
Contract | Punchout | Flag
NaN | NaN | False
NaN | Computer Information | True
Non-CLM0_Cat_01 | NaN | True
这里np.where
不是必需的,只需使用~
与Series.isna
反转掩码:
req_line['Catalog_Flag'] = ~(req_line['Contract'].isna() & req_line['Punchout'].isna())
如果没有缺失值,则像测试一样工作|
对于Series.notna
的按位OR
:
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
使用Series.isna
来识别nan
:
req_line['Catalog_Flag'] = np.where(req_line['Contract'].isna() & req_line['Punchout'].isna(), False, True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.