0

I am trying to have a code that does the following:

#create a new column in a dataframe 
df['new_column'] = 0

and for every row in this dataframe, it looks at whether column B's value is 1. If it is, it populates the new column with a 1, it then jumps 126 rows forward, and populates that row of the new column with a -1; otherwise, it populates the row of the new column with a 0. Once done that, the formula should continue from a row that would depend on the value encountered in the column B (i.e., if in the first iteration, column B's value=1, the row from which the loop restarts will be 127, alternatively it would be row 2)

for row in df.iterrows():
    for item in df['new_column']:
        if df.B[df.new_column[df.new_column.index[item]]] == 1:
            item = 1
            row += 126
            item = -1
        else:
            item = 0

Problem is that I get: "TypeError: can only concatenate tuple (not "int") to tuple". Could you please help me?

gianluca
  • 57
  • 1
  • 2
  • 6
  • You're looking for `df_zing.iterrows()`. – IanS Mar 19 '19 at 14:22
  • 3
    Also, your code is badly indented. – IanS Mar 19 '19 at 14:23
  • thanks! What's the indentation mistake? I know iterrows, but I cannot understand how to use it here – gianluca Mar 19 '19 at 14:26
  • 3
    Possible duplicate of [How to iterate over rows in a DataFrame in Pandas?](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) – mad_ Mar 19 '19 at 14:27
  • Regarding the indentation mistake, the second loop (and everything below it) should be indented, as it is inside the first loop. – IanS Mar 19 '19 at 14:28
  • I personally find `iterrows` and `itertuples` not entirely intuitive to use. I suggest you read the documentation and ask a new question when you're stuck again. – IanS Mar 19 '19 at 14:28
  • the problem with tuples is that when I use tuples I cannot add an integer to rows: row += 126. It tells me that I need to concatenate a tuple (not "int") to a tuple. How can I tell it to skip the 126 rows then? – gianluca Mar 19 '19 at 14:48

0 Answers0