LdM
LdM

Reputation: 704

Iterations through rows

I am a bit confused on how to use both while and for loop. What I would like to achieve is the following:

I set a threshold = 2 and initialize the counter n to 0. I tried this logic:

    while n <= threshold:  # need to keep the while loop
      for x in df['Value']:  # need to keep the for loop
        # create new columns by sum      
        n=n+1 # increase the counter by 1

For instance: I have

Value
1
2
3

Since n=0 is smaller than the threshold (2), I create a new column with the sum:

Value Sum
1      1
2      2
3      3

I go with n=1, so I will have

Value Sum  Sum1
1      1     2
2      2     4
3      3     6

and so on (in this example, until n=2). My desired output would be

Value Sum  Sum1 Sum2
1      1     2   4
2      2     4   8
3      3     6   12

The problem with my code is that it doesn't stop when the threshold is reached.

Upvotes: 1

Views: 63

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71689

IIUC, A simple for loop along with sum would suffice

for i in range(threshold+1):
    df[f'Sum{i}'] = df.sum(1)

Alternatively you can try a more efficient Numpy Approach

a = df['Value'].values[:, None] * 2 ** np.r_[:threshold + 1]
df.join(pd.DataFrame(a).add_prefix('Sum'))

   Value  Sum0  Sum2  Sum3
0      1     1     2     4
1      2     2     4     8
2      3     3     6    12

Upvotes: 2

Related Questions