2016-04-08 23 views
0

我有一個列表y,其中包含nan每個後面的實數,以防止線條在matplotlib中繪製時加入。我可以嘗試通過屏蔽nan數據來與np.isfinite()作圖。但是,當它們大於5時,我可以忽略nan - 因此,在超過5個nan s的區域中不會發生線連接。 pandas已經內置series.fillna(limit=2)這似乎很理想,但我不想取代nan。我真的需要一個例子來說明如何做到這一點。在matplotlib中加入NaN值

我想要的輸出結果如下(7到14之間的差距)。

import matplotlib.pyplot as plt 
import numpy as np 
x = np.arange(20) 
y = [np.nan, 5, np.nan, np.nan, 3, np.nan, 10, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 2, np.nan, 7, np.nan, 22, np.nan, 15, np.nan] 

plt.plot(x,y, '-') 

enter image description here

回答

1

我沒有看到一個乾淨地矢量化這一點。

如果你真的只點了一把,只寫一個循環做

def brute_force_clean_nans(x, y): 
    x_clean, y_clean = [], [] 
    cnt = 0 
    for _x, _y in zip(x, y): 
     if np.isnan(_y): 
      cnt += 1 
      if cnt == 5: 
       # on the 5th nan, put it in the list to break line 
       x_clean.append(_x) 
       y_clean.append(_y) 
      continue 
     cnt = 0 
     x_clean.append(_x) 
     y_clean.append(_y) 
    return x_clean, y_clean 

你也可以做的事情有np.where,看着奔跑等,但如果你有這幾點它可能不值得。

+0

我還沒有試過你的代碼,但是我有160多個數據超過20,000的系列。不確定是否可行,以循環每一個數據點。我會在稍後讓你知道 – Curtis

+0

我已更正了包含錯誤的代碼。除此之外,非常感謝您解決我的問題! – Curtis

+0

對不起,錯字。 – tacaswell