我来自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)
谢谢!
答案 0 :(得分:1)
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
])
答案 1 :(得分:1)
根据@ 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))]
希望这有帮助。
答案 2 :(得分:0)
我不知道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的输出 最后你应该附加较长列表的其余项目。
答案 3 :(得分:0)
如果你正在使用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)]