3

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 Answers1

3

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.

sophocles
  • 13,593
  • 3
  • 14
  • 33
  • sorry for not being entirely clear, deal_pos_code is one column. The other number is what I want to generate (what you have referred to as pos_code_x) so the only comparison I can draw is if the deal_pos_code number increases. – BenniBenassi Feb 21 '21 at 11:38
  • I have changed my answer so that it is clearer. Now you can see only the columns 'deal', and you are able to generate the column 'pos_code' using the code in the answer. – sophocles Feb 21 '21 at 11:49
  • I understand now thanks. In some of my earlier code I've made the deal column rows have the attribute type of a string, just figuring out how to convert them back to integers and this should hopefully work. – BenniBenassi Feb 21 '21 at 12:08
  • there's many ways to convert the dtype of your 'deal' column, check this link out: https://stackoverflow.com/questions/15891038/change-column-type-in-pandas. I can update my answer if you want to incorporate that. – sophocles Feb 21 '21 at 12:11
  • 1
    I finally got it sorted! Thank you so much for helping me! – BenniBenassi Feb 21 '21 at 12:30