简体   繁体   English

如何根据条件在 pandas 中创建另一列?

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

I have two columns - Punchout and Contract.我有两列 - Punchout 和 Contract。 I want a catalog flag column where it is FALSE if Punchout and Contract both are NAN otherwise it is TRUE.我想要一个目录标志列,如果 Punchout 和 Contract 都是 NAN,则它是 FALSE,否则它是 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 "=="?但它抛出的错误是: 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

Here np.where is not necessary, just use ~ for invert mask with Series.isna :这里np.where不是必需的,只需使用~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 :对于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

Use Series.isna for identifying nan :使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM