0
votes

I need to calculate the B columns and I wanted to do that using a for loop. It's calculation is a a static column (Col2) multiplied by the previous column (A) while also adding in the B column. Intended Results

for i in range(df.shape[1], 3, -1):
    bcol = (df['Col2']*df.iloc[:,i]).round(decimals=1)
    df.insert(i, 'B', bcol, allow_duplicates=True)

Error I get: "single positional indexer is out-of-bounds

1
It's common when using a backwards range to forget that it will start with the starting number. If df.shape[1] is 9, then i will start at 9, but the valid indexes are only 0 through 8. Add a -1 there. - Tim Roberts
You need to stay within the dimension of the dataset Read this - Gerhard

1 Answers

0
votes

Does this help your answer?

arr = [1,2,3,4,5]
for i in range(1,5):
    print (f"Index{i-1} - Index{i} = {arr[i] - arr[i-1]}"

You can use this logic for 2-D matrix also by iterating all the values in column then iterate over rows