简体   繁体   中英

Create Dataframe column that increases count based on another columns value

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM