0

I have dataset that the column is datetime type, I have converted its column to object type for easier checking. In this case, i want to check any column whatever the value are equal to 1, but if the column there are not any value or NaN are equal to 0. Example;

Year1.       |    Year.2     |    Year.3      |
12-01-2021         NaN              NaN
NaN             11-01-2021       12-02-2020

I want the result is:

Year1.       |    Year.2     |    Year.3      |
  1                 0               0
  0                 1               1

Anyone can help me to solve this case? Thank you in advance

2 Answers2

0

I think you can use either math.isnan(x), np.isnan(x) or pd.isna(x) (depending on which library you're already using. Check each value of your table against one of these functions, and it will return 1 for a NaN, and 0 for a normal value. See related issue

mand
  • 129
  • 1
  • 13
0

Assign the values where you are not having nan as 1 using df.where and then fill nan with 0 try:

df = df.where(df.isna(),1).fillna(0)

df:

    Year1.  Year.2  Year.3
0   1       0       0
1   0       1       1
Pygirl
  • 12,969
  • 5
  • 30
  • 43