单个位置索引器超出范围错误

时间:2020-09-05 09:16:26

标签: python excel dataframe dictionary for-loop

我有两个字典,每个字典有206个项目。每个团队都是一个数据框。查看图片以了解其中的词典和项目。

Keys in both the dictionaries are same and are as shown here in the image

My Dictionaries 'voltage' and 'copy'

我要替换“电压”字典的所有表中的“容量”值,如下所示

x = (total number of rows in the sheet )/25

Capacity Value in Row1(index=0) - the sum of the values from Rows 1 to x in 
                                   "Current" column of 'copy'
Capacity Value in Row2(index=1) - the sum of the values from Rows x to 2*x in 
                                   "Current" column of 'copy'
Capacity Value in Row3(index=2) - the sum of the values from Rows 2*x to 3*x 
                                   in "Current" column of 'copy'
.
.
.
Capacity Value in Row25(index=24) - the sum of the values from Rows 24*x to 
                                     the last value.

要执行此操作,我编写了如下代码:

   for sheet in voltage:    
   for sheet in copy:
    n = ( round((len(copy[sheet]))/25) )
    
    for k in range(0,24):
        p = 1+((k+1)*(n))
        
        if k == 24:
            voltage[sheet]['Capacity'].iloc[k] = copy[sheet]['Current'].iloc[((k)*(n)):].sum()
        else:
            voltage[sheet]['Capacity'].iloc[k] = copy[sheet]['Current'].iloc[((k)*(n)+1):(p)].sum()

以上代码无效。所以我试图将代码分成两部分

    for sheet in voltage:    
    for sheet in copy:
    n = ( round((len(copy[sheet]))/25) )
    
    for k in range(0,24):
        p = 1+((k+1)*(n))
        voltage[sheet]['Capacity'].iloc[k] = copy[sheet]['Current'].iloc[((k)*(n)+1):(p)].sum()

有了这个,我可以在所有工作表的“容量”列中填充24行。对于第二十五行,我写了下面的

    for sheet in voltage:    
    for sheet in copy:
    n = ( round((len(copy[sheet]))/25) )
    
    voltage[sheet]['Capacity'].iloc[24] = copy[sheet]['Current'].iloc[((24*n)+1):].sum()

但是,它仍然显示相同的错误消息。两种情况下的错误消息都是相同的。请帮助我。

谢谢:) Error Message in both the cases

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为excel表中列名“ Current”下的某些数据丢失了。将数据添加到excel工作表后,我就可以正常工作。