循环嵌套问题 - 值不正确

时间:2017-05-31 13:49:49

标签: python loops pandas numpy if-statement

我有一个包含两个相关列的数据框(实际上有> 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,但如果您在径向位置彼此相等时手动计算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']

1 个答案:

答案 0 :(得分: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