How to group a dataframe and summarize over subgroups of consecutive numbers in Python?












3














I have a dataframe with a column containing ids and other column containing numbers:



df1 = {'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]}


You may note that each Id has their correponding series of consecutive numbers in the column "Number". For example:



Id 400 contains a series of length 4 {1, 2, 3, 4} and another of length 2 {8, 9}



I´d like to obtain for each Id, the average length of their corresponding series.
In this example:



df2 = {'ID':[400, 500], 'avg_length':[3, 2]}


Any ideas will be much appreciated!










share|improve this question



























    3














    I have a dataframe with a column containing ids and other column containing numbers:



    df1 = {'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
    'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]}


    You may note that each Id has their correponding series of consecutive numbers in the column "Number". For example:



    Id 400 contains a series of length 4 {1, 2, 3, 4} and another of length 2 {8, 9}



    I´d like to obtain for each Id, the average length of their corresponding series.
    In this example:



    df2 = {'ID':[400, 500], 'avg_length':[3, 2]}


    Any ideas will be much appreciated!










    share|improve this question

























      3












      3








      3







      I have a dataframe with a column containing ids and other column containing numbers:



      df1 = {'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
      'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]}


      You may note that each Id has their correponding series of consecutive numbers in the column "Number". For example:



      Id 400 contains a series of length 4 {1, 2, 3, 4} and another of length 2 {8, 9}



      I´d like to obtain for each Id, the average length of their corresponding series.
      In this example:



      df2 = {'ID':[400, 500], 'avg_length':[3, 2]}


      Any ideas will be much appreciated!










      share|improve this question













      I have a dataframe with a column containing ids and other column containing numbers:



      df1 = {'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
      'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]}


      You may note that each Id has their correponding series of consecutive numbers in the column "Number". For example:



      Id 400 contains a series of length 4 {1, 2, 3, 4} and another of length 2 {8, 9}



      I´d like to obtain for each Id, the average length of their corresponding series.
      In this example:



      df2 = {'ID':[400, 500], 'avg_length':[3, 2]}


      Any ideas will be much appreciated!







      python pandas pandas-groupby group-summaries






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 16:29









      Facundo IannelloFacundo Iannello

      182




      182
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Here is one way, uses groupby twice,



          df1['tmp'] = (df1.Number - df1.Number.shift() > 1).cumsum()

          df1.groupby(['ID', 'tmp']).Number.count().groupby(level = 0).mean().reset_index(name = 'avg_length')

          2.29 ms ± 75.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

          ID avg_length
          0 400 3
          1 500 2


          Option 2: Without using apply twice, still uses tmp column created earlier



          df1.groupby('ID').tmp.apply(lambda x: x.value_counts().mean()).reset_index(name = 'avg_length')

          2.25 ms ± 99.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)





          share|improve this answer































            1















            groupby + cumsum + value_counts



            You can use groupby with a custom function:



            df = pd.DataFrame({'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
            'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]})

            def mean_count(x):
            return (x - x.shift()).ne(1).cumsum().value_counts().mean()

            res = df.groupby('ID')['Number'].apply(mean_count).reset_index()

            print(res)

            ID Number
            0 400 3.0
            1 500 2.0





            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%2f53416534%2fhow-to-group-a-dataframe-and-summarize-over-subgroups-of-consecutive-numbers-in%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              Here is one way, uses groupby twice,



              df1['tmp'] = (df1.Number - df1.Number.shift() > 1).cumsum()

              df1.groupby(['ID', 'tmp']).Number.count().groupby(level = 0).mean().reset_index(name = 'avg_length')

              2.29 ms ± 75.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

              ID avg_length
              0 400 3
              1 500 2


              Option 2: Without using apply twice, still uses tmp column created earlier



              df1.groupby('ID').tmp.apply(lambda x: x.value_counts().mean()).reset_index(name = 'avg_length')

              2.25 ms ± 99.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)





              share|improve this answer




























                1














                Here is one way, uses groupby twice,



                df1['tmp'] = (df1.Number - df1.Number.shift() > 1).cumsum()

                df1.groupby(['ID', 'tmp']).Number.count().groupby(level = 0).mean().reset_index(name = 'avg_length')

                2.29 ms ± 75.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

                ID avg_length
                0 400 3
                1 500 2


                Option 2: Without using apply twice, still uses tmp column created earlier



                df1.groupby('ID').tmp.apply(lambda x: x.value_counts().mean()).reset_index(name = 'avg_length')

                2.25 ms ± 99.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)





                share|improve this answer


























                  1












                  1








                  1






                  Here is one way, uses groupby twice,



                  df1['tmp'] = (df1.Number - df1.Number.shift() > 1).cumsum()

                  df1.groupby(['ID', 'tmp']).Number.count().groupby(level = 0).mean().reset_index(name = 'avg_length')

                  2.29 ms ± 75.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

                  ID avg_length
                  0 400 3
                  1 500 2


                  Option 2: Without using apply twice, still uses tmp column created earlier



                  df1.groupby('ID').tmp.apply(lambda x: x.value_counts().mean()).reset_index(name = 'avg_length')

                  2.25 ms ± 99.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)





                  share|improve this answer














                  Here is one way, uses groupby twice,



                  df1['tmp'] = (df1.Number - df1.Number.shift() > 1).cumsum()

                  df1.groupby(['ID', 'tmp']).Number.count().groupby(level = 0).mean().reset_index(name = 'avg_length')

                  2.29 ms ± 75.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

                  ID avg_length
                  0 400 3
                  1 500 2


                  Option 2: Without using apply twice, still uses tmp column created earlier



                  df1.groupby('ID').tmp.apply(lambda x: x.value_counts().mean()).reset_index(name = 'avg_length')

                  2.25 ms ± 99.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 21 '18 at 17:00

























                  answered Nov 21 '18 at 16:48









                  VaishaliVaishali

                  18.2k31029




                  18.2k31029

























                      1















                      groupby + cumsum + value_counts



                      You can use groupby with a custom function:



                      df = pd.DataFrame({'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
                      'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]})

                      def mean_count(x):
                      return (x - x.shift()).ne(1).cumsum().value_counts().mean()

                      res = df.groupby('ID')['Number'].apply(mean_count).reset_index()

                      print(res)

                      ID Number
                      0 400 3.0
                      1 500 2.0





                      share|improve this answer


























                        1















                        groupby + cumsum + value_counts



                        You can use groupby with a custom function:



                        df = pd.DataFrame({'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
                        'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]})

                        def mean_count(x):
                        return (x - x.shift()).ne(1).cumsum().value_counts().mean()

                        res = df.groupby('ID')['Number'].apply(mean_count).reset_index()

                        print(res)

                        ID Number
                        0 400 3.0
                        1 500 2.0





                        share|improve this answer
























                          1












                          1








                          1







                          groupby + cumsum + value_counts



                          You can use groupby with a custom function:



                          df = pd.DataFrame({'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
                          'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]})

                          def mean_count(x):
                          return (x - x.shift()).ne(1).cumsum().value_counts().mean()

                          res = df.groupby('ID')['Number'].apply(mean_count).reset_index()

                          print(res)

                          ID Number
                          0 400 3.0
                          1 500 2.0





                          share|improve this answer













                          groupby + cumsum + value_counts



                          You can use groupby with a custom function:



                          df = pd.DataFrame({'ID':[400, 400, 400, 400, 400, 400, 500, 500, 500, 500], 
                          'Number':[1, 2, 3, 4, 8, 9, 22, 23, 26, 27]})

                          def mean_count(x):
                          return (x - x.shift()).ne(1).cumsum().value_counts().mean()

                          res = df.groupby('ID')['Number'].apply(mean_count).reset_index()

                          print(res)

                          ID Number
                          0 400 3.0
                          1 500 2.0






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 21 '18 at 16:56









                          jppjpp

                          93.8k2055106




                          93.8k2055106






























                              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%2f53416534%2fhow-to-group-a-dataframe-and-summarize-over-subgroups-of-consecutive-numbers-in%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

                              Tonle Sap (See)

                              I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                              Guatemaltekische Davis-Cup-Mannschaft