I have a pandas data frame with column A:
A |
---|
5 |
1 |
NaN |
12 |
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 |
---|---|
5 | True |
1 | True |
NaN | False |
12 | True |
13 | True |
NaN | False |
NaN | False |
Thanks
CodePudding user response:
Use notna
:
df['B'] = df['A'].notna()
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
CodePudding user response:
Use the .isna()
(or .isnull()
) method to determine if the value is Nan
. It returns True
for Nan
and False
for the rest, so we need to negate that. Negation is done with ~
operator.
df['B'] = ~df['A'].isna()