Pandas: fill one column with count of # of obs between occurrences in a 2nd columnCounting consecutive positive value in Python arrayCount the number occurrences of a character in a stringHow can I count the occurrences of a list item?Selecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrameChange data type of columns in PandasHow do I get the row count of a pandas DataFrame?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers

How to help new students accept function notation

Pandas: fill one column with count of # of obs between occurrences in a 2nd column

Is The Lion King live action film made in motion capture?

Is multiplication of real numbers uniquely defined as being distributive over addition?

As a 16 year old, how can I keep my money safe from my mother?

During the Space Shuttle Columbia Disaster of 2003, Why Did The Flight Director Say, "Lock the doors."?

English - Acceptable use of parentheses in an author's name

Why couldn't soldiers sight their own weapons without officers' orders?

Is it true that control+alt+delete only became a thing because IBM would not build Bill Gates a computer with a task manager button?

Atari ST DRAM timing puzzle

How to query data in backups?

What is a "Genuine Geraldo interviewee"?

How do I explain to a team that the project they will work on for six months will 100% fail?

Dropdowns & Chevrons for Right to Left languages

Geometric programming: Why are the constraints defined to be less than/equal to 1?

Can a PC attack themselves with an unarmed strike?

QGIS 3.6 Vector Affine Transformation

Is this cheap "air conditioner" able to cool a room?

Is it double speak?

Can ads on a page read my password?

New computer from Dell with pre-installed Ubuntu won't boot. Should I assume it's an error from Dell?

How to say "fit" in Latin?

How to display a duet in lyrics?

Non-OR journals which regularly publish OR research



Pandas: fill one column with count of # of obs between occurrences in a 2nd column


Counting consecutive positive value in Python arrayCount the number occurrences of a character in a stringHow can I count the occurrences of a list item?Selecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrameChange data type of columns in PandasHow do I get the row count of a pandas DataFrame?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















Say I have the following DataFrame which has a 0/1 entry depending on whether something happened/didn't happen within a certain month.



Y = [0,0,1,1,0,0,0,0,1,1,1]
X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

df = pd.DataFrame('R': Y,index = X)



R
2010-01-01 0
2010-02-01 0
2010-03-01 1
2010-04-01 1
2010-05-01 0
2010-06-01 0
2010-07-01 0
2010-08-01 0
2010-09-01 1
2010-10-01 1
2010-11-01 1


What I want is to create a 2nd column that lists the # of months until the next occurrence of a 1.



That is, I need:



 R F
2010-01-01 0 2
2010-02-01 0 1
2010-03-01 1 0
2010-04-01 1 0
2010-05-01 0 4
2010-06-01 0 3
2010-07-01 0 2
2010-08-01 0 1
2010-09-01 1 0
2010-10-01 1 0
2010-11-01 1 0


What I've tried: I haven't gotten far, but I'm able to fill the first bit



A = list(df.index)
T = df[df['R']==1]

a = df.index[0]
b = T.index[0]
c = A.index(b) - A.index(a)

df.loc[a:b, 'F'] = np.linspace(c,0,c+1)

R F
2010-01-01 0 2.0
2010-02-01 0 1.0
2010-03-01 1 0.0
2010-04-01 1 NaN
2010-05-01 0 NaN
2010-06-01 0 NaN
2010-07-01 0 NaN
2010-08-01 0 NaN
2010-09-01 1 NaN
2010-10-01 1 NaN
2010-11-01 1 NaN


EDIT Probably would have been better to provide an original example that spanned multiple years.



Y = [0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1]
X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

df = pd.DataFrame('R': Y,index = X)









share|improve this question
































    7















    Say I have the following DataFrame which has a 0/1 entry depending on whether something happened/didn't happen within a certain month.



    Y = [0,0,1,1,0,0,0,0,1,1,1]
    X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

    df = pd.DataFrame('R': Y,index = X)



    R
    2010-01-01 0
    2010-02-01 0
    2010-03-01 1
    2010-04-01 1
    2010-05-01 0
    2010-06-01 0
    2010-07-01 0
    2010-08-01 0
    2010-09-01 1
    2010-10-01 1
    2010-11-01 1


    What I want is to create a 2nd column that lists the # of months until the next occurrence of a 1.



    That is, I need:



     R F
    2010-01-01 0 2
    2010-02-01 0 1
    2010-03-01 1 0
    2010-04-01 1 0
    2010-05-01 0 4
    2010-06-01 0 3
    2010-07-01 0 2
    2010-08-01 0 1
    2010-09-01 1 0
    2010-10-01 1 0
    2010-11-01 1 0


    What I've tried: I haven't gotten far, but I'm able to fill the first bit



    A = list(df.index)
    T = df[df['R']==1]

    a = df.index[0]
    b = T.index[0]
    c = A.index(b) - A.index(a)

    df.loc[a:b, 'F'] = np.linspace(c,0,c+1)

    R F
    2010-01-01 0 2.0
    2010-02-01 0 1.0
    2010-03-01 1 0.0
    2010-04-01 1 NaN
    2010-05-01 0 NaN
    2010-06-01 0 NaN
    2010-07-01 0 NaN
    2010-08-01 0 NaN
    2010-09-01 1 NaN
    2010-10-01 1 NaN
    2010-11-01 1 NaN


    EDIT Probably would have been better to provide an original example that spanned multiple years.



    Y = [0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1]
    X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

    df = pd.DataFrame('R': Y,index = X)









    share|improve this question




























      7












      7








      7








      Say I have the following DataFrame which has a 0/1 entry depending on whether something happened/didn't happen within a certain month.



      Y = [0,0,1,1,0,0,0,0,1,1,1]
      X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

      df = pd.DataFrame('R': Y,index = X)



      R
      2010-01-01 0
      2010-02-01 0
      2010-03-01 1
      2010-04-01 1
      2010-05-01 0
      2010-06-01 0
      2010-07-01 0
      2010-08-01 0
      2010-09-01 1
      2010-10-01 1
      2010-11-01 1


      What I want is to create a 2nd column that lists the # of months until the next occurrence of a 1.



      That is, I need:



       R F
      2010-01-01 0 2
      2010-02-01 0 1
      2010-03-01 1 0
      2010-04-01 1 0
      2010-05-01 0 4
      2010-06-01 0 3
      2010-07-01 0 2
      2010-08-01 0 1
      2010-09-01 1 0
      2010-10-01 1 0
      2010-11-01 1 0


      What I've tried: I haven't gotten far, but I'm able to fill the first bit



      A = list(df.index)
      T = df[df['R']==1]

      a = df.index[0]
      b = T.index[0]
      c = A.index(b) - A.index(a)

      df.loc[a:b, 'F'] = np.linspace(c,0,c+1)

      R F
      2010-01-01 0 2.0
      2010-02-01 0 1.0
      2010-03-01 1 0.0
      2010-04-01 1 NaN
      2010-05-01 0 NaN
      2010-06-01 0 NaN
      2010-07-01 0 NaN
      2010-08-01 0 NaN
      2010-09-01 1 NaN
      2010-10-01 1 NaN
      2010-11-01 1 NaN


      EDIT Probably would have been better to provide an original example that spanned multiple years.



      Y = [0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1]
      X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

      df = pd.DataFrame('R': Y,index = X)









      share|improve this question
















      Say I have the following DataFrame which has a 0/1 entry depending on whether something happened/didn't happen within a certain month.



      Y = [0,0,1,1,0,0,0,0,1,1,1]
      X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

      df = pd.DataFrame('R': Y,index = X)



      R
      2010-01-01 0
      2010-02-01 0
      2010-03-01 1
      2010-04-01 1
      2010-05-01 0
      2010-06-01 0
      2010-07-01 0
      2010-08-01 0
      2010-09-01 1
      2010-10-01 1
      2010-11-01 1


      What I want is to create a 2nd column that lists the # of months until the next occurrence of a 1.



      That is, I need:



       R F
      2010-01-01 0 2
      2010-02-01 0 1
      2010-03-01 1 0
      2010-04-01 1 0
      2010-05-01 0 4
      2010-06-01 0 3
      2010-07-01 0 2
      2010-08-01 0 1
      2010-09-01 1 0
      2010-10-01 1 0
      2010-11-01 1 0


      What I've tried: I haven't gotten far, but I'm able to fill the first bit



      A = list(df.index)
      T = df[df['R']==1]

      a = df.index[0]
      b = T.index[0]
      c = A.index(b) - A.index(a)

      df.loc[a:b, 'F'] = np.linspace(c,0,c+1)

      R F
      2010-01-01 0 2.0
      2010-02-01 0 1.0
      2010-03-01 1 0.0
      2010-04-01 1 NaN
      2010-05-01 0 NaN
      2010-06-01 0 NaN
      2010-07-01 0 NaN
      2010-08-01 0 NaN
      2010-09-01 1 NaN
      2010-10-01 1 NaN
      2010-11-01 1 NaN


      EDIT Probably would have been better to provide an original example that spanned multiple years.



      Y = [0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1]
      X = pd.date_range(start = "2010", freq = "MS", periods = len(Y))

      df = pd.DataFrame('R': Y,index = X)






      python pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 8 hours ago







      measure_theory

















      asked 9 hours ago









      measure_theorymeasure_theory

      3601 silver badge14 bronze badges




      3601 silver badge14 bronze badges

























          4 Answers
          4






          active

          oldest

          votes


















          6














          Here is my way



          s=df.R.cumsum()
          df.loc[df.R==0,'F']=s.groupby(s).cumcount(ascending=False)+1
          df.F.fillna(0,inplace=True)

          df
          Out[12]:
          R F
          2010-01-01 0 2.0
          2010-02-01 0 1.0
          2010-03-01 1 0.0
          2010-04-01 1 0.0
          2010-05-01 0 4.0
          2010-06-01 0 3.0
          2010-07-01 0 2.0
          2010-08-01 0 1.0
          2010-09-01 1 0.0
          2010-10-01 1 0.0
          2010-11-01 1 0.0





          share|improve this answer
































            4














            Create a series containing your dates, mask this series when your R series is not equal to 1, bfill, and subtract!




            u = df.index.to_series()

            ii = u.where(df.R.eq(1)).bfill()

            12 * (ii.dt.year - u.dt.year) + (ii.dt.month - u.dt.month)




            2010-01-01 2
            2010-02-01 1
            2010-03-01 0
            2010-04-01 0
            2010-05-01 4
            2010-06-01 3
            2010-07-01 2
            2010-08-01 1
            2010-09-01 0
            2010-10-01 0
            2010-11-01 0
            Freq: MS, dtype: int64





            share|improve this answer



























            • @measure_theory fixed!

              – user3483203
              8 hours ago


















            2














            Here is a way that worked for me, not as elegant as @user3483203 but it does the job.



            df['F'] = 0 
            for i in df.index:
            j = i
            while df.loc[j, 'R'] == 0:
            df.loc[i, 'F'] =df.loc[i, 'F'] + 1
            j=j+1
            df


            ################
            Out[39]:
            index R F
            0 2010-01-01 0 2
            1 2010-02-01 0 1
            2 2010-03-01 1 0
            3 2010-04-01 1 0
            4 2010-05-01 0 4
            5 2010-06-01 0 3
            6 2010-07-01 0 2
            7 2010-08-01 0 1
            8 2010-09-01 1 0
            9 2010-10-01 1 0
            10 2010-11-01 1 0

            In [40]:





            share|improve this answer

























            • This actually works if the DataFrame spans multiple years

              – measure_theory
              8 hours ago



















            1














            My take



            s = (df.R.diff().ne(0) | df.R.eq(1)).cumsum()
            s.groupby(s).transform(lambda s: np.arange(len(s),0,-1) if len(s)>1 else 0)



            2010-01-01 2
            2010-02-01 1
            2010-03-01 0
            2010-04-01 0
            2010-05-01 4
            2010-06-01 3
            2010-07-01 2
            2010-08-01 1
            2010-09-01 0
            2010-10-01 0
            2010-11-01 0
            Freq: MS, Name: R, dtype: int64





            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57431667%2fpandas-fill-one-column-with-count-of-of-obs-between-occurrences-in-a-2nd-colu%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              6














              Here is my way



              s=df.R.cumsum()
              df.loc[df.R==0,'F']=s.groupby(s).cumcount(ascending=False)+1
              df.F.fillna(0,inplace=True)

              df
              Out[12]:
              R F
              2010-01-01 0 2.0
              2010-02-01 0 1.0
              2010-03-01 1 0.0
              2010-04-01 1 0.0
              2010-05-01 0 4.0
              2010-06-01 0 3.0
              2010-07-01 0 2.0
              2010-08-01 0 1.0
              2010-09-01 1 0.0
              2010-10-01 1 0.0
              2010-11-01 1 0.0





              share|improve this answer





























                6














                Here is my way



                s=df.R.cumsum()
                df.loc[df.R==0,'F']=s.groupby(s).cumcount(ascending=False)+1
                df.F.fillna(0,inplace=True)

                df
                Out[12]:
                R F
                2010-01-01 0 2.0
                2010-02-01 0 1.0
                2010-03-01 1 0.0
                2010-04-01 1 0.0
                2010-05-01 0 4.0
                2010-06-01 0 3.0
                2010-07-01 0 2.0
                2010-08-01 0 1.0
                2010-09-01 1 0.0
                2010-10-01 1 0.0
                2010-11-01 1 0.0





                share|improve this answer



























                  6












                  6








                  6







                  Here is my way



                  s=df.R.cumsum()
                  df.loc[df.R==0,'F']=s.groupby(s).cumcount(ascending=False)+1
                  df.F.fillna(0,inplace=True)

                  df
                  Out[12]:
                  R F
                  2010-01-01 0 2.0
                  2010-02-01 0 1.0
                  2010-03-01 1 0.0
                  2010-04-01 1 0.0
                  2010-05-01 0 4.0
                  2010-06-01 0 3.0
                  2010-07-01 0 2.0
                  2010-08-01 0 1.0
                  2010-09-01 1 0.0
                  2010-10-01 1 0.0
                  2010-11-01 1 0.0





                  share|improve this answer













                  Here is my way



                  s=df.R.cumsum()
                  df.loc[df.R==0,'F']=s.groupby(s).cumcount(ascending=False)+1
                  df.F.fillna(0,inplace=True)

                  df
                  Out[12]:
                  R F
                  2010-01-01 0 2.0
                  2010-02-01 0 1.0
                  2010-03-01 1 0.0
                  2010-04-01 1 0.0
                  2010-05-01 0 4.0
                  2010-06-01 0 3.0
                  2010-07-01 0 2.0
                  2010-08-01 0 1.0
                  2010-09-01 1 0.0
                  2010-10-01 1 0.0
                  2010-11-01 1 0.0






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  WeNYoBenWeNYoBen

                  152k8 gold badges53 silver badges84 bronze badges




                  152k8 gold badges53 silver badges84 bronze badges


























                      4














                      Create a series containing your dates, mask this series when your R series is not equal to 1, bfill, and subtract!




                      u = df.index.to_series()

                      ii = u.where(df.R.eq(1)).bfill()

                      12 * (ii.dt.year - u.dt.year) + (ii.dt.month - u.dt.month)




                      2010-01-01 2
                      2010-02-01 1
                      2010-03-01 0
                      2010-04-01 0
                      2010-05-01 4
                      2010-06-01 3
                      2010-07-01 2
                      2010-08-01 1
                      2010-09-01 0
                      2010-10-01 0
                      2010-11-01 0
                      Freq: MS, dtype: int64





                      share|improve this answer



























                      • @measure_theory fixed!

                        – user3483203
                        8 hours ago















                      4














                      Create a series containing your dates, mask this series when your R series is not equal to 1, bfill, and subtract!




                      u = df.index.to_series()

                      ii = u.where(df.R.eq(1)).bfill()

                      12 * (ii.dt.year - u.dt.year) + (ii.dt.month - u.dt.month)




                      2010-01-01 2
                      2010-02-01 1
                      2010-03-01 0
                      2010-04-01 0
                      2010-05-01 4
                      2010-06-01 3
                      2010-07-01 2
                      2010-08-01 1
                      2010-09-01 0
                      2010-10-01 0
                      2010-11-01 0
                      Freq: MS, dtype: int64





                      share|improve this answer



























                      • @measure_theory fixed!

                        – user3483203
                        8 hours ago













                      4












                      4








                      4







                      Create a series containing your dates, mask this series when your R series is not equal to 1, bfill, and subtract!




                      u = df.index.to_series()

                      ii = u.where(df.R.eq(1)).bfill()

                      12 * (ii.dt.year - u.dt.year) + (ii.dt.month - u.dt.month)




                      2010-01-01 2
                      2010-02-01 1
                      2010-03-01 0
                      2010-04-01 0
                      2010-05-01 4
                      2010-06-01 3
                      2010-07-01 2
                      2010-08-01 1
                      2010-09-01 0
                      2010-10-01 0
                      2010-11-01 0
                      Freq: MS, dtype: int64





                      share|improve this answer















                      Create a series containing your dates, mask this series when your R series is not equal to 1, bfill, and subtract!




                      u = df.index.to_series()

                      ii = u.where(df.R.eq(1)).bfill()

                      12 * (ii.dt.year - u.dt.year) + (ii.dt.month - u.dt.month)




                      2010-01-01 2
                      2010-02-01 1
                      2010-03-01 0
                      2010-04-01 0
                      2010-05-01 4
                      2010-06-01 3
                      2010-07-01 2
                      2010-08-01 1
                      2010-09-01 0
                      2010-10-01 0
                      2010-11-01 0
                      Freq: MS, dtype: int64






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 8 hours ago

























                      answered 8 hours ago









                      user3483203user3483203

                      37.3k8 gold badges31 silver badges60 bronze badges




                      37.3k8 gold badges31 silver badges60 bronze badges















                      • @measure_theory fixed!

                        – user3483203
                        8 hours ago

















                      • @measure_theory fixed!

                        – user3483203
                        8 hours ago
















                      @measure_theory fixed!

                      – user3483203
                      8 hours ago





                      @measure_theory fixed!

                      – user3483203
                      8 hours ago











                      2














                      Here is a way that worked for me, not as elegant as @user3483203 but it does the job.



                      df['F'] = 0 
                      for i in df.index:
                      j = i
                      while df.loc[j, 'R'] == 0:
                      df.loc[i, 'F'] =df.loc[i, 'F'] + 1
                      j=j+1
                      df


                      ################
                      Out[39]:
                      index R F
                      0 2010-01-01 0 2
                      1 2010-02-01 0 1
                      2 2010-03-01 1 0
                      3 2010-04-01 1 0
                      4 2010-05-01 0 4
                      5 2010-06-01 0 3
                      6 2010-07-01 0 2
                      7 2010-08-01 0 1
                      8 2010-09-01 1 0
                      9 2010-10-01 1 0
                      10 2010-11-01 1 0

                      In [40]:





                      share|improve this answer

























                      • This actually works if the DataFrame spans multiple years

                        – measure_theory
                        8 hours ago
















                      2














                      Here is a way that worked for me, not as elegant as @user3483203 but it does the job.



                      df['F'] = 0 
                      for i in df.index:
                      j = i
                      while df.loc[j, 'R'] == 0:
                      df.loc[i, 'F'] =df.loc[i, 'F'] + 1
                      j=j+1
                      df


                      ################
                      Out[39]:
                      index R F
                      0 2010-01-01 0 2
                      1 2010-02-01 0 1
                      2 2010-03-01 1 0
                      3 2010-04-01 1 0
                      4 2010-05-01 0 4
                      5 2010-06-01 0 3
                      6 2010-07-01 0 2
                      7 2010-08-01 0 1
                      8 2010-09-01 1 0
                      9 2010-10-01 1 0
                      10 2010-11-01 1 0

                      In [40]:





                      share|improve this answer

























                      • This actually works if the DataFrame spans multiple years

                        – measure_theory
                        8 hours ago














                      2












                      2








                      2







                      Here is a way that worked for me, not as elegant as @user3483203 but it does the job.



                      df['F'] = 0 
                      for i in df.index:
                      j = i
                      while df.loc[j, 'R'] == 0:
                      df.loc[i, 'F'] =df.loc[i, 'F'] + 1
                      j=j+1
                      df


                      ################
                      Out[39]:
                      index R F
                      0 2010-01-01 0 2
                      1 2010-02-01 0 1
                      2 2010-03-01 1 0
                      3 2010-04-01 1 0
                      4 2010-05-01 0 4
                      5 2010-06-01 0 3
                      6 2010-07-01 0 2
                      7 2010-08-01 0 1
                      8 2010-09-01 1 0
                      9 2010-10-01 1 0
                      10 2010-11-01 1 0

                      In [40]:





                      share|improve this answer













                      Here is a way that worked for me, not as elegant as @user3483203 but it does the job.



                      df['F'] = 0 
                      for i in df.index:
                      j = i
                      while df.loc[j, 'R'] == 0:
                      df.loc[i, 'F'] =df.loc[i, 'F'] + 1
                      j=j+1
                      df


                      ################
                      Out[39]:
                      index R F
                      0 2010-01-01 0 2
                      1 2010-02-01 0 1
                      2 2010-03-01 1 0
                      3 2010-04-01 1 0
                      4 2010-05-01 0 4
                      5 2010-06-01 0 3
                      6 2010-07-01 0 2
                      7 2010-08-01 0 1
                      8 2010-09-01 1 0
                      9 2010-10-01 1 0
                      10 2010-11-01 1 0

                      In [40]:






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 8 hours ago









                      Mohamed NidabdellaMohamed Nidabdella

                      4013 silver badges12 bronze badges




                      4013 silver badges12 bronze badges















                      • This actually works if the DataFrame spans multiple years

                        – measure_theory
                        8 hours ago


















                      • This actually works if the DataFrame spans multiple years

                        – measure_theory
                        8 hours ago

















                      This actually works if the DataFrame spans multiple years

                      – measure_theory
                      8 hours ago






                      This actually works if the DataFrame spans multiple years

                      – measure_theory
                      8 hours ago












                      1














                      My take



                      s = (df.R.diff().ne(0) | df.R.eq(1)).cumsum()
                      s.groupby(s).transform(lambda s: np.arange(len(s),0,-1) if len(s)>1 else 0)



                      2010-01-01 2
                      2010-02-01 1
                      2010-03-01 0
                      2010-04-01 0
                      2010-05-01 4
                      2010-06-01 3
                      2010-07-01 2
                      2010-08-01 1
                      2010-09-01 0
                      2010-10-01 0
                      2010-11-01 0
                      Freq: MS, Name: R, dtype: int64





                      share|improve this answer





























                        1














                        My take



                        s = (df.R.diff().ne(0) | df.R.eq(1)).cumsum()
                        s.groupby(s).transform(lambda s: np.arange(len(s),0,-1) if len(s)>1 else 0)



                        2010-01-01 2
                        2010-02-01 1
                        2010-03-01 0
                        2010-04-01 0
                        2010-05-01 4
                        2010-06-01 3
                        2010-07-01 2
                        2010-08-01 1
                        2010-09-01 0
                        2010-10-01 0
                        2010-11-01 0
                        Freq: MS, Name: R, dtype: int64





                        share|improve this answer



























                          1












                          1








                          1







                          My take



                          s = (df.R.diff().ne(0) | df.R.eq(1)).cumsum()
                          s.groupby(s).transform(lambda s: np.arange(len(s),0,-1) if len(s)>1 else 0)



                          2010-01-01 2
                          2010-02-01 1
                          2010-03-01 0
                          2010-04-01 0
                          2010-05-01 4
                          2010-06-01 3
                          2010-07-01 2
                          2010-08-01 1
                          2010-09-01 0
                          2010-10-01 0
                          2010-11-01 0
                          Freq: MS, Name: R, dtype: int64





                          share|improve this answer













                          My take



                          s = (df.R.diff().ne(0) | df.R.eq(1)).cumsum()
                          s.groupby(s).transform(lambda s: np.arange(len(s),0,-1) if len(s)>1 else 0)



                          2010-01-01 2
                          2010-02-01 1
                          2010-03-01 0
                          2010-04-01 0
                          2010-05-01 4
                          2010-06-01 3
                          2010-07-01 2
                          2010-08-01 1
                          2010-09-01 0
                          2010-10-01 0
                          2010-11-01 0
                          Freq: MS, Name: R, dtype: int64






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 8 hours ago









                          rafaelcrafaelc

                          32.9k9 gold badges33 silver badges55 bronze badges




                          32.9k9 gold badges33 silver badges55 bronze badges






























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57431667%2fpandas-fill-one-column-with-count-of-of-obs-between-occurrences-in-a-2nd-colu%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                              Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                              François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480