2017-06-24 31 views
0

例如,這是數據表:使用Python數據劃分成不同的時間間隔(間隔基於另一列的值)

1.1  300 
1.5  200 
1.7  234 
2.4  356 
2.8  234 
3.4  456 

我想把值在第2列到相應的間隔,像第一三到1.0-2.0區間,下兩到2.0-3.0區間,最後一個到3.0-4.0區間。除此之外,在每個區間中,我希望返回大於底部90%值但小於相應區間中頂部10%值的值(假設實際情況下每個區間中有很多數字)。

我想要輸出的是一個新的表,它有2列:第1列是區間邊界的中間值,第2列是在上一段中提到的值。示例數據表的輸出爲:

1.5 300 
2.5 356 
3.5 456 

謝謝!

+0

那你試試? –

+0

@Pedro von Hertwig我可以用numpy來達到這個目的嗎? – StopHorseAtEdge

+0

「將第二列中的值放入相應的時間間隔」是什麼意思?您是指每個「int」都有一個單獨的數據框,或者是帶有間隔標籤的第三列......給出一個更清晰的示例預期的結果是。 –

回答

0

這是你想要的嗎?

import numpy as _np 
def bin_data(x, y, bins=[1.,2.,3.,4.]): 
    """ 
    """ 
    import warnings 
    import numpy as np 

    xmin=np.min(x) 
    xmax=np.max(x) 

    bins_number=len(bins)-1 
    xsm = np.mean([bins[:-1], bins[1:]], axis=0) 
    ysm = np.zeros(bins_number) 



    #----------- 
    # The following process is what actually bins the data using numpy 
    with warnings.catch_warnings(): 
     warnings.simplefilter("ignore", category=RuntimeWarning) 
     for i in range(bins_number): 
      if i == bins_number - 1: 
       sel = bins[i] <= x 
      else: 
       sel = (bins[i] <= x) & (x < bins[i+1]) 
      ysm[i] = np.percentile(y[sel], 90, interpolation='nearest') 
    #----------- 

    return xsm, ysm 

輸出現在是正確的:

In [25]: bin_data(x, y) 
Out[25]: (array([ 1.5, 2.5, 3.5]), array([ 300., 356., 456.])) 
+0

謝謝!這是我的錯,x和y是numpy.array而不是列表。 – StopHorseAtEdge