0

I have data frame like this:

Data | Value |
1.01 |   1   | 
2.01 |   Na  | 
3.01 |   Na  |  
4.01 |   Na  | 
5.01 |   1   | 
6.01 |   Na  | 
7.01 |   Na  | 
8.01 |   1   | 

I would like to add new column with label, where label change incrementally based on column Value. If there is a changed in column value then ther should be next label.

Data | Value | Label
1.01 |   1   |  1
2.01 |   Na  |  2
3.01 |   Na  |  2
4.01 |   Na  |  2
5.01 |   1   |  3
6.01 |   Na  |  4
7.01 |   Na  |  4
8.01 |   1   |  5

How to do it in pandas python avoiding iterating by row? Thx

1 Answers1

0

IIUC comapre shifted values for not equal with cumulative sum and assign to new column Label:

df['Label'] = df['Value'].ne(df['Value'].shift()).cumsum()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252