简体   繁体   English

根据另一列中的 NaN 值创建新列

[英]Create a new column based on NaN values in another column

I have a pandas data frame with column A :我有一个带有A列的 pandas 数据框:

A一个
5 5
1 1
NaN
12 12
13 13
NaN
NaN

how can I create a new column B based on A to give True if the value is known and False if the value is NaN with an output like this:如果值是已知的,我如何基于A创建一个新的列B ,如果值是 NaN,则给出 True,output 如下所示:

A一个 B
5 5 True真的
1 1 True真的
NaN False错误的
12 12 True真的
13 13 True真的
NaN False错误的
NaN False错误的

Thanks谢谢

Use notna :使用notna

df['B'] = df['A'].notna()

output: output:

      A      B
0   5.0   True
1   1.0   True
2   NaN  False
3  12.0   True
4  13.0   True
5   NaN  False
6   NaN  False

Use the .isna() (or .isnull() ) method to determine if the value is Nan .使用.isna() (或.isnull() )方法确定值是否为Nan It returns True for Nan and False for the rest, so we need to negate that.它为Nan返回True ,为 rest 返回False ,所以我们需要否定它。 Negation is done with ~ operator.否定是用~运算符完成的。

df['B'] = ~df['A'].isna()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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