Alessandrini
Alessandrini

Reputation: 191

Increment dataframe column based on condition

I have a dataframe and I want to create a new column based on a condition on a different column. Create the new column "ans" with 1 and increment based on the column "ix". In the "ix" column if the value is the same as the next one keep the "ans" column the same and if its different increment "ans"

Thank you for your answer, I am new to Python so I am not sure how to do this

      index   ix  
        1     pa 
        2     pa
        3     pa
        4     pe
        5     fc
        6     pb
        7     pb
        8     df

should result in:-

      index   ix  ans
        1     pa   1
        2     pa   1
        3     pa   1
        4     pe   2
        5     fc   3
        6     pb   4
        7     pb   4
        8     df   5

Upvotes: 3

Views: 4027

Answers (1)

unutbu
unutbu

Reputation: 879093

In [47]: df['ans'] = (df['ix'] != df['ix'].shift(1)).cumsum()

In [48]: df
Out[48]: 
   index  ix  ans
0      1  pa    1
1      2  pa    1
2      3  pa    1
3      4  pe    2
4      5  fc    3
5      6  pb    4
6      7  pb    4
7      8  df    5

Upvotes: 10

Related Questions