【问题标题】:replace nan in list of list在列表列表中替换 nan
【发布时间】:2021-07-16 02:41:38
【问题描述】:

我正在尝试从列表中替换 nan。我已经尝试过这些解决方案。

Replace all elements in a list from list of lists

但是,我收到以下错误:TypeError: ufunc 'isnan' not supported for the input types,并且无法根据强制转换安全地将输入强制转换为任何支持的类型

list_of_lists=[[1,2,3],['nan','nan','nan'],[3,4,5]]

我想用“replaced”之类的字符串替换 nan 并期望:

list_of_lists=[[1,2,3],['replaced','replaced','replaced'],[3,4,5]]

感谢您的帮助

【问题讨论】:

  • 你试过列表理解吗?
  • 显示你的实际输入列表,这里的nan显然不是字符串,我猜是np.nan
  • 我的nan是个float nan,我没认出来

标签: python list nan


【解决方案1】:

您将nan 表示为字符串,这不是正确的表示, 您可以使用float('nan')math.nan 无论如何,考虑到这一点,您可以执行以下操作:

>> from math import nan, isnan
>> list_of_lists=[[1,2,3],[nan, nan, nan],[3,4,5]]
>> [['replaced' if isnan(i) else i for i in j ] for j in list_of_lists]

输出

[[1, 2, 3], ['replaced', 'replaced', 'replaced'], [3, 4, 5]]

【讨论】:

    【解决方案2】:

    这是一种非常简单的方法。

    new_list = [y.replace('nan','replace') if y == 'nan' else y for x in list_of_lists for y in x  ]
    

    输出

    [1, 2, 3, 'replace', 'replace', 'replace', 3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2020-04-02
      • 2019-07-28
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多