Pandas: How to obtain top 2, middle 2 and bottom 2 rows in a each group












3















Let's say I have a dataframe df as below. To obtain 1st 2 and last 2 in each group I have used groupby.nth



df = pd.DataFrame({'A': ['a','a','a','a','a','a','a','a','b','b','b','b','b','b','b'],
'B': [1, 2, 3, 4, 5,6,7,8,1, 2, 3, 4, 5,6,7]}, columns=['A', 'B'])
df.groupby('A').nth([0,1,-2,-1])


Result:



    B
A
a 1
a 2
a 7
a 8
b 1
b 2
b 6
b 7


I'm not sure how to obtain the middle 2 rows. For example, in group 'A' there are 8 instances so my middle would be 4, 5 (n/2, n/2+1) and group 'B' my middle rows would be 3, 4 (n/2-0.5, n/2+0.5). Any guidance is appreciated.










share|improve this question





























    3















    Let's say I have a dataframe df as below. To obtain 1st 2 and last 2 in each group I have used groupby.nth



    df = pd.DataFrame({'A': ['a','a','a','a','a','a','a','a','b','b','b','b','b','b','b'],
    'B': [1, 2, 3, 4, 5,6,7,8,1, 2, 3, 4, 5,6,7]}, columns=['A', 'B'])
    df.groupby('A').nth([0,1,-2,-1])


    Result:



        B
    A
    a 1
    a 2
    a 7
    a 8
    b 1
    b 2
    b 6
    b 7


    I'm not sure how to obtain the middle 2 rows. For example, in group 'A' there are 8 instances so my middle would be 4, 5 (n/2, n/2+1) and group 'B' my middle rows would be 3, 4 (n/2-0.5, n/2+0.5). Any guidance is appreciated.










    share|improve this question



























      3












      3








      3








      Let's say I have a dataframe df as below. To obtain 1st 2 and last 2 in each group I have used groupby.nth



      df = pd.DataFrame({'A': ['a','a','a','a','a','a','a','a','b','b','b','b','b','b','b'],
      'B': [1, 2, 3, 4, 5,6,7,8,1, 2, 3, 4, 5,6,7]}, columns=['A', 'B'])
      df.groupby('A').nth([0,1,-2,-1])


      Result:



          B
      A
      a 1
      a 2
      a 7
      a 8
      b 1
      b 2
      b 6
      b 7


      I'm not sure how to obtain the middle 2 rows. For example, in group 'A' there are 8 instances so my middle would be 4, 5 (n/2, n/2+1) and group 'B' my middle rows would be 3, 4 (n/2-0.5, n/2+0.5). Any guidance is appreciated.










      share|improve this question
















      Let's say I have a dataframe df as below. To obtain 1st 2 and last 2 in each group I have used groupby.nth



      df = pd.DataFrame({'A': ['a','a','a','a','a','a','a','a','b','b','b','b','b','b','b'],
      'B': [1, 2, 3, 4, 5,6,7,8,1, 2, 3, 4, 5,6,7]}, columns=['A', 'B'])
      df.groupby('A').nth([0,1,-2,-1])


      Result:



          B
      A
      a 1
      a 2
      a 7
      a 8
      b 1
      b 2
      b 6
      b 7


      I'm not sure how to obtain the middle 2 rows. For example, in group 'A' there are 8 instances so my middle would be 4, 5 (n/2, n/2+1) and group 'B' my middle rows would be 3, 4 (n/2-0.5, n/2+0.5). Any guidance is appreciated.







      pandas pandas-groupby






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 6:23









      Aqueous Carlos

      374314




      374314










      asked Nov 15 '18 at 3:33









      psangampsangam

      444




      444
























          2 Answers
          2






          active

          oldest

          votes


















          2














          sacul's answer is nice , Here I just follow your own idea def a customize function



          def middle(x):
          if len(x) % 2 == 0:
          return x.iloc[int(len(x) / 2) - 1:int(len(x) / 2) + 1]
          else:
          return x.iloc[int((len(x) / 2 - 0.5)) - 1:int(len(x) / 2 + 0.5)]

          pd.concat([middle(y) for _ , y in df.groupby('A')])
          Out[25]:
          A B
          3 a 4
          4 a 5
          10 b 3
          11 b 4





          share|improve this answer































            2














            You can use iloc to find the n//2 -1 and n//2 indices for each group (// is floor division):



            g = df.groupby('A')

            g.apply(lambda x: x['B'].iloc[[len(x)//2-1, len(x)//2]])

            A
            a 3 4
            4 5
            b 10 3
            11 4
            Name: B, 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%2f53312044%2fpandas-how-to-obtain-top-2-middle-2-and-bottom-2-rows-in-a-each-group%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









              2














              sacul's answer is nice , Here I just follow your own idea def a customize function



              def middle(x):
              if len(x) % 2 == 0:
              return x.iloc[int(len(x) / 2) - 1:int(len(x) / 2) + 1]
              else:
              return x.iloc[int((len(x) / 2 - 0.5)) - 1:int(len(x) / 2 + 0.5)]

              pd.concat([middle(y) for _ , y in df.groupby('A')])
              Out[25]:
              A B
              3 a 4
              4 a 5
              10 b 3
              11 b 4





              share|improve this answer




























                2














                sacul's answer is nice , Here I just follow your own idea def a customize function



                def middle(x):
                if len(x) % 2 == 0:
                return x.iloc[int(len(x) / 2) - 1:int(len(x) / 2) + 1]
                else:
                return x.iloc[int((len(x) / 2 - 0.5)) - 1:int(len(x) / 2 + 0.5)]

                pd.concat([middle(y) for _ , y in df.groupby('A')])
                Out[25]:
                A B
                3 a 4
                4 a 5
                10 b 3
                11 b 4





                share|improve this answer


























                  2












                  2








                  2







                  sacul's answer is nice , Here I just follow your own idea def a customize function



                  def middle(x):
                  if len(x) % 2 == 0:
                  return x.iloc[int(len(x) / 2) - 1:int(len(x) / 2) + 1]
                  else:
                  return x.iloc[int((len(x) / 2 - 0.5)) - 1:int(len(x) / 2 + 0.5)]

                  pd.concat([middle(y) for _ , y in df.groupby('A')])
                  Out[25]:
                  A B
                  3 a 4
                  4 a 5
                  10 b 3
                  11 b 4





                  share|improve this answer













                  sacul's answer is nice , Here I just follow your own idea def a customize function



                  def middle(x):
                  if len(x) % 2 == 0:
                  return x.iloc[int(len(x) / 2) - 1:int(len(x) / 2) + 1]
                  else:
                  return x.iloc[int((len(x) / 2 - 0.5)) - 1:int(len(x) / 2 + 0.5)]

                  pd.concat([middle(y) for _ , y in df.groupby('A')])
                  Out[25]:
                  A B
                  3 a 4
                  4 a 5
                  10 b 3
                  11 b 4






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 3:51









                  Wen-BenWen-Ben

                  114k83368




                  114k83368

























                      2














                      You can use iloc to find the n//2 -1 and n//2 indices for each group (// is floor division):



                      g = df.groupby('A')

                      g.apply(lambda x: x['B'].iloc[[len(x)//2-1, len(x)//2]])

                      A
                      a 3 4
                      4 5
                      b 10 3
                      11 4
                      Name: B, dtype: int64





                      share|improve this answer






























                        2














                        You can use iloc to find the n//2 -1 and n//2 indices for each group (// is floor division):



                        g = df.groupby('A')

                        g.apply(lambda x: x['B'].iloc[[len(x)//2-1, len(x)//2]])

                        A
                        a 3 4
                        4 5
                        b 10 3
                        11 4
                        Name: B, dtype: int64





                        share|improve this answer




























                          2












                          2








                          2







                          You can use iloc to find the n//2 -1 and n//2 indices for each group (// is floor division):



                          g = df.groupby('A')

                          g.apply(lambda x: x['B'].iloc[[len(x)//2-1, len(x)//2]])

                          A
                          a 3 4
                          4 5
                          b 10 3
                          11 4
                          Name: B, dtype: int64





                          share|improve this answer















                          You can use iloc to find the n//2 -1 and n//2 indices for each group (// is floor division):



                          g = df.groupby('A')

                          g.apply(lambda x: x['B'].iloc[[len(x)//2-1, len(x)//2]])

                          A
                          a 3 4
                          4 5
                          b 10 3
                          11 4
                          Name: B, dtype: int64






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 15 '18 at 3:55

























                          answered Nov 15 '18 at 3:48









                          sacuLsacuL

                          30.5k41942




                          30.5k41942






























                              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%2f53312044%2fpandas-how-to-obtain-top-2-middle-2-and-bottom-2-rows-in-a-each-group%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

                              Florida Star v. B. J. F.

                              Error while running script in elastic search , gateway timeout

                              Adding quotations to stringified JSON object values