how to check if a value is not na in python

To check if a value is not NA in Python using Pandas library, we can use notna() function which returns a boolean mask indicating where the values in a DataFrame are not NA.

Here is an example:

main.py
import pandas as pd
 
# create a pandas series with some NA values
s = pd.Series([1, 2, 3, np.nan, 5, np.nan])
 
# use notna() function to check which values are not NA
mask = s.notna()
 
# print the original series and the mask
print(s)
print(mask)
250 chars
12 lines

Output:

main.py
0    1.0
1    2.0
2    3.0
3    NaN
4    5.0
5    NaN
dtype: float64

0     True
1     True
2     True
3    False
4     True
5    False
dtype: bool
148 chars
16 lines

In the code above, we create a Pandas series s with some NA values, then we use the notna() function to create a boolean mask mask indicating which values are not NA. Finally, we print both the original series and the mask to see the results.

We can also use isna() function to check if a value is NA. It will return the opposite of notna() function.

related categories

gistlibby LogSnag