2017-05-31 140 views
0

我有一個數據框有兩個相關的列(實際上有> 2,但不認爲這很重要),並且其中一列有重複。循環嵌套問題 - 值不正確

重複項位於列HAB_slice ['Radial Position']中,並以0.1爲增量。

理想情況下,我想說如果HAB_slice ['Radial Position']中的兩個值彼此相等,找到它們之間的絕對值差並將它們添加到運行總數中。

當前的代碼看起來是這樣的:

possible_pos = np.linspace(0, 1, 1/stepsize+1) 
    center_sum = 0 
    for i in range(0, len(possible_pos)): 
     temp = HAB_slice[HAB_slice['Radial Position']==possible_pos[i]] 
     if len(temp) == 2: 
      center_sum += np.abs(temp['I'].diff().values[1]) 
    print center_sum 

雖然它返回一個值,並不會引發錯誤,center_sum值比我手動計算它的不同。我認爲這只是嵌套有問題,但我很新的循環,我不確定。

錯誤示例:以下數據在此代碼中會生成一個center_sum = 0,但是如果您在Radial位置彼此相等時手動計算I中的絕對值差異,則它等於0.0045878。

I   Radial Position 
0.14289522 1 
0.14298554 0.9 
0.1430356 0.8 
0.1430454 0.7 
0.1430552 0.6 
0.14266456 0.5 
0.14227392 0.4 
0.14234106 0.3 
0.14286598 0.2 
0.1433909 0.1 
0.14309062 0 
0.14279034 0.1 
0.14271344 0.2 
0.14285992 0.3 
0.1430064 0.4 
0.14327248 0.5 
0.14353856 0.6 
0.14356664 0.7 
0.14335672 0.8 
0.1431468 0.9 
0.14338368 1 

編輯:我用示例代碼簡化了事情,試着讓它工作。

test1 = [[0.14309062,0],[0.1433909,0.1], [0.14286598,0.2], [0.14234106,0.3], 
[0.14279034,0.1], [0.14271344,0.2], [0.14285992,0.3]] 
''' 
test2 = [[0.14289522,1],[0.14298554,0.9],[0.1430356,0.8],[0.1430454,0.7], 
[0.1430552,0.6],[0.14266456,0.5],[0.14227392,0.4],[0.14234106,0.3], 
[0.14286598,0.2],[0.1433909,0.1],[0.14309062,0],[0.14279034,0.1], 
[0.14271344,0.2],[0.14285992,0.3],[0.1430064,0.4],[0.14327248,0.5], 
[0.14353856,0.6],[0.14356664,0.7],[0.14335672,0.8],[0.1431468,0.9], 
[0.14338368,1]] 
''' 
stepsize = 0.1 
possible_pos = np.linspace(0, 1, 1/stepsize+1) 
HAB_slice = pd.DataFrame(test1) 
HAB_slice.columns = ['I', 'Radial Position'] 
+0

聞起來像漂浮點問題。 – Divakar

回答

0

請嘗試以下代碼。它應該工作。

possible_pos = np.linspace(0, 1, 1/stepsize+1) 
center_sum = 0 

for i in range(0, len(possible_pos)): 

    # retriving index position of the step value 
    indices = [i for i, x in enumerate(HAB_slice['Radial Position']) if x == possible_pos[i]] 

    # if multiple value exist for the postion 
    if len(indices) > 1: 
     values = [x for i, x in enumerate(HAB_slice['I']) if i in indices] 
     center_sum += np.abs(np.diff(values)) 

    # if single value exist for the position 
    elif len(indices) == 1: 
     center_sum += HAB_slice['I'][indices[0]] 

    # if no value exist for the position 
    else: continue 

print center_sum 
+0

感謝您的幫助!當我使用該代碼時,出現索引錯誤:索引11超出定義索引的行的大小爲11的軸0的界限。由於我不知道我在做什麼,所以我甚至不知道從哪裏開始尋找它所抱怨的問題。 – ShellieJ

+0

由[[0.14309062,0],[0.1433909,0.1],[0.14286598,0.2],[0.14234106,0.3],[0.14279034,0.1],[0.14271344,0.2],[0.14285992,0.3]]縮短的測試用例,它不會出錯,但它也爲center_sum提供了兩個值,而不是一個,它們都不對應於手形計算值0.00127196 – ShellieJ

+0

i中「i for i,x」是當前索引位置(計數器)步驟值。 enumerate()函數將一個計數器作爲(counter,element)添加到列表中。 – sam23