【问题标题】:Remove an item if value is NaT from list of dictionaries?如果字典列表中的值为 NaT,则删除一个项目?
【发布时间】:2021-07-11 08:55:07
【问题描述】:

如何从字典列表中删除 NaT 值。

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

最终输出

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

如果值为NaT,则time 键的数据类型为pandas._libs.tslibs.nattype.NaTType

【问题讨论】:

    标签: python pandas list numpy


    【解决方案1】:

    使用带有notna过滤器的dict理解嵌套列表:

    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'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多