1

I'm trying to create a list which have a values which are either zero or one (if the values in the table's column is Null or not). But my list only contains ones.

list = []
for i in range(len(df['DefaultDate'])):
  if df['DefaultDate'][i] == 'nan':
    list.append(0)
  else:
    list.append(1)
print(list)
print(df['DefaultDate'])
0

3 Answers 3

0

You are checking for the string "nan", not for the special NaN values. You can replace that ENTIRE code sequence with:

valid = ~df['DefaultDate'].isnull()
0

Right now you compare your dataframe element with the string "nan". To check whether it is "Not a Number" (NaN) you have to compare it with numpy.nan or use .isnull() :

import numpy as np
list = []
for i in range(len(df['DefaultDate'])):
  if df['DefaultDate'][i] == np.nan:
    list.append(0)
  else:
    list.append(1)
print(list)
print(df['DefaultDate'])
0

Use .isnull() or .notnull() to check. Then convert to int and use .tolist().

df['DefaultDate'].notnull().astype(int).tolist()
2
  • Kindly, I would like to know what exactly astype and tolist functions will do in order to integrate to my code Oct 22, 2022 at 20:27
  • notnull() returns a pandas.Series of True/False values. astype(int) converts them to 1/0. tolist() returns a list (instead of a Series)
    – bitflip
    Oct 22, 2022 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.