Counter Column in Pandas DataFrame where it changes based on other column

Question:

How do I go about adding a new column in a pandas dataframe, where I want the column to have a counter based on anothers column criteria, for example (desired output shown):

    WeekCounter  DayofWeeek
    1            Monday
    1            Monday
    1            Tuesday
    1            Sunday
    2            Monday
    2            Wednesday
    2            Thursday
    2            Sunday
    3            Monday
    3            Monday
    3            Monday

How do I create a column that acts as a counter whenever the column value changes from Sunday to Monday? My original attempt would be a for loop with a nested if statement, but is there a more pandas-native manner in accomplishing this?

Asked By: Harold Chaw

||

Answers:

Check whether the current row is “Monday” when the previous row is “Sunday” to generate a boolean mask. Then, perform a cumsum on the result.

df['WeekCounter'] = (df.DayofWeek.eq('Monday') 
        & df.DayofWeek.shift().eq('Sunday')).cumsum() + 1

df

    WeekCounter  DayofWeek
0             1     Monday
1             1     Monday
2             1    Tuesday
3             1     Sunday
4             2     Monday
5             2  Wednesday
6             2   Thursday
7             2     Sunday
8             3     Monday
9             3     Monday
10            3     Monday
Answered By: cs95

How can I group this code with groupby, single column??

productos_stock[‘AGOTADOS’] = (productos_stock[‘CANTIDAD EN MANO’].eq(0) & productos_stock[‘CANTIDAD EN MANO’].shift().gt(1)).cumsum() + 1

Answered By: Alejandro Verdugo