1

I am using pandas Python library and I am very stuck with nested loop.

I want to run a calculation for every row - that is fine:

for i, row in df_merged.iterrows():

My data looks like this:

product price   max_move_%
  1     100      10

and then nest another loop in range of value from the column from data frame for a given row like something like this:

for a in range((df_merged['max_move'][row])* (- 1)), (df_merged['max_move'][row])):

So that I get

product price   max_move_%  true_move     price_new
1       100      10          -10            90
1       100      10          -9             91
 .....
1       100      10          10             110

is it even possible in dataframes? To use particular value from a df in the loop>

I am getting this type of error:

 ---------------------------------------------------------------------------
 TypeError                                 Traceback (most recent call last)
 <ipython-input-51-9c87df3fd221> in <module>()
       2 
       3 for i, row in df_merged.iterrows():
----> 4     for h in range(((df_merged['max_move_%'][row]) * (- 1), (df_merged['max_move_%'][row]))):
  5        print('ok')
  6 

 TypeError: 'tuple' object cannot be interpreted as an integer

Thank you!

1 Answer 1

1

df.iterrows() gives you a tuple where i is the index and row is the Series corresponding to the index. The way you want to use your inner loop, you should use the index and not the Series :

   for a in range((df_merged['max_move_%'][i]) * (- 1), df_merged['max_move_%'][i]):

Maybe more elegant, you could also directly use the row series :

   for a in range((row['max_move_%']) * (- 1), row['max_move_%']):
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Julien, I changed it to integer and it is OK : df_merged['max_move_%'] = df_merged['max_move_%'].astype(np.int64)
Perfect. You can also use np.arange if you want to manipulate floats.
Hi Julien, please dont you know even the solution to the adding values to the dataframe? So that the data from the first loop are converted together with new value to the dataframe? I tried this for i, row in df_merged.iterrows(): for a in range((row['max_move_%']) * (- 1), row['max_move_%']): df_merged['price_new'] = df_merged['price'] * (1 - a / 100.00) but nothing happened

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.