0

I need to add a column to my dataframe that will add a number each time a value in another column surpasses a limit. Example below:

Original DF:

ColA   ColB
 4      1.4
 10     0.5
 1      2.3
 3      12.2
 8.8    8.5
 2      5.2
 0.6    0.33
 9      3
 4      144
 33     8

Desired DF: Where value in ColB surpasses 10, ColC count = count +1

ColA   ColB     ColC
 4      1.4       1
 10     0.5       1
 1      2.3       1
 3      12.2      2
 8.8    8.5       2
 2      5.2       2
 0.6    0.33      2
 9      3         2
 4      144       3
 33     8         3

thank you for the help!

1 Answer 1

1
df['ColC'] = (df['ColB'] > 10).cumsum() + 1
print(df)

Prints:

   ColA    ColB  ColC
0   4.0    1.40     1
1  10.0    0.50     1
2   1.0    2.30     1
3   3.0   12.20     2
4   8.8    8.50     2
5   2.0    5.20     2
6   0.6    0.33     2
7   9.0    3.00     2
8   4.0  144.00     3
9  33.0    8.00     3
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your comment. This works but I forgot to add that I have another column that I will need to groupby then use this function. How can I groupby another column and apply this function?
@dmd7 you can do df['ColC'] = df.groupby('<column name>')['ColB'].transform(lambda x: (x > 10).cumsum()+1)

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.