Remove an item if value is NaT from list of dictionaries?

Viewed 358

How to remove a NaT value from list of dictionaries.

a = [{'subject':'Maths','name':'marcus','time':Timestamp('2020-08-31 11:26:28.230000')},
{'subject':'Maths','name':'paul','time':NaT}]

Final Output

a = [{'subject':'Maths','name':'marcus','time':Timestamp('2020-08-31 11:26:28.230000')},
{'subject':'Maths','name':'paul'}]

DataType of time key if value is NaT is pandas._libs.tslibs.nattype.NaTType

1 Answers

Use nested list with dict comprehension with notna filter:

b = [{k:v for k, v in d.items() if pd.notna(v)} for d in a]
print (b)
[{'subject': 'Maths', 'name': 'marcus', 'time': Timestamp('2020-08-31 11:26:28.230000')},
 {'subject': 'Maths', 'name': 'paul'}]
Related