How to iterate through rows and add number increments based on whether a number in a column increases

Viewed 82

I want to be able to iterate through the rows in my data frame and be able to replace the current number with an +1 incremental number (that starts @ 1000) every time the number changes.

Here is my dataframe column with the desired number next to it:

deal_pos_code
657 > 1000
680 > 1001
694 > 1002
694 > 1002
694 > 1002
694 > 1002
695 > 1003
695 > 1003
695 > 1003
695 > 1003
696 > 1004
696 > 1004

Update

I am new but this is what I have so far:

cv = df['deal_pos_code'].iloc[0]
nv = 1000

for i, row in mbn.iterrows():
    if mbn.row['deal_pos_code'] == cv:
        row['deal_pos_code'] = nv     
    else:
        nv +=
        cv = row['deal_pos_code']
        row['deal_pos_code'] = nv

I am getting an attribute error: AttributeError: 'DataFrame' object has no attribute 'row'

Update.. bottom lines fixed on table

1 Answers

You can check the difference between each row in your 'deal' variable compared to previous row using diff, and if it is not 0 (i.e. increasing in your case), use cumsum(), and add(999):

df['pos_code'] = (df['deal'].diff() != 0).cumsum().add(999)

df
    deal  pos_code
0    657      1000
1    680      1001
2    694      1002
3    694      1002
4    694      1002
5    694      1002
6    695      1003
7    695      1003
8    695      1003
9    695      1003
10   696      1004
11   696      1004

As @Shubham pointed out, there's probably a typo in your last two rows.

Related