【问题标题】:python: eliminate positions of nan in multiple listspython:消除多个列表中nan的位置
【发布时间】:2015-04-16 13:04:20
【问题描述】:

我来自 IDL,并试图在两个数据列表中查找和消除 NaN。假设列表 A 的位置 5 中有一个 NaN,但列表 B 没有。我需要在两个列表中删除位置 5。就这样……

A = [1, NaN, 3, 4, NaN, 6, 7, 8, 9]

B = [1', 2', 3', NaN, 5', 6', 7', 8', NaN]

A_new = [1 , 3 , 6 , 7 , 8 ]

B_new = [1', 3', 6', 7', 8']

这是运行良好的 IDL 代码。我只需要将它翻译成 python,我就很难过。

;Removes the NANs

loc = where((Finite(pdcsapflux) EQ 1)and(Finite(time) EQ 1))

flux_nonan = pdcsapflux(loc)

time_nonan = time(loc)

谢谢!!

【问题讨论】:

  • 1' 是什么?请更正您的代码..
  • 一个素数。只是某种数据的占位符。我想将它与 A 中的 1 区分开来。它可以是任何类型的有限值
  • 如果您来自 IDL,您可能希望使用 numpypandas 而不是纯 Python 列表。
  • @ThomasCannon 当你说NaN 时,你是说None 还是1/0 之类的东西?
  • 是的!对不起。我正是我的意思。无

标签: python list nan idl-programming-language


【解决方案1】:

如果您使用 numpy,您也可以不使用 where 函数(如果您使用大型矩阵,通常会非常慢)

import numpy as np 
A = np.array([1, NaN, 3, 4, NaN, 6, 7, 8, 9])
B = np.array([1, 2, 3, NaN, 5, 6, 7, 8, NaN])
A_new = A[~np.isnan(A)]
B_new = B[~np.isnan(B)]

【讨论】:

    【解决方案2】:

    根据@DSM 的建议,如果您来自 IDL,您可能希望将 numpy 用于实际数组,而不是列表。使用 numpy 直接替换 IDL 代码更像如下:

    import numpy.random as ran
    import numpy as np
    arr = ran.rand(10)  # create some fake data
    arr[[1,3,5]] = np.nan  # add some "bad" values
    arr2 = arr[np.where(~np.isnan(arr))]
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:
      A = [1, None, 3, 4, None, 6, 7, 8, 9]
      B = [1, 2, 3, None, 5, 6, 7, 8, None]
      print zip(*[
          (a, b) for a, b in zip(A, B)
          if a is not None and b is not None
      ])
      

      Documentation of zip

      【讨论】:

        【解决方案4】:

        我不知道python是否有NaN,假设是None。

        ta, tb = [], []
        for i in range(min(len(a), len(b))):
            if a[i] is None or b[i] is None:
                continue
            ta.append(a[i])
            tb.append(b[i])
        

        ta, tb 是 a,b 的输出 最后,您应该附加较长列表的其余项目。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-21
          • 1970-01-01
          • 1970-01-01
          • 2021-12-22
          • 2021-12-31
          • 1970-01-01
          • 2014-01-27
          • 1970-01-01
          相关资源
          最近更新 更多