How to select several continue rows with interval in pandas?












1















I want to select 3 rows every 5 rows. For example, the first 5 rows, I want to remain the last 3 rows.



Input:



import pandas as pd 
df = pd.DataFrame({'a': np.arange(16)})
print(df)


Output:



     a
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14


Expected:



     a
2 2
3 3
4 4
7 7
8 8
9 9
12 12
13 13
14 14


Hopefully for help!










share|improve this question



























    1















    I want to select 3 rows every 5 rows. For example, the first 5 rows, I want to remain the last 3 rows.



    Input:



    import pandas as pd 
    df = pd.DataFrame({'a': np.arange(16)})
    print(df)


    Output:



         a
    0 0
    1 1
    2 2
    3 3
    4 4
    5 5
    6 6
    7 7
    8 8
    9 9
    10 10
    11 11
    12 12
    13 13
    14 14


    Expected:



         a
    2 2
    3 3
    4 4
    7 7
    8 8
    9 9
    12 12
    13 13
    14 14


    Hopefully for help!










    share|improve this question

























      1












      1








      1


      0






      I want to select 3 rows every 5 rows. For example, the first 5 rows, I want to remain the last 3 rows.



      Input:



      import pandas as pd 
      df = pd.DataFrame({'a': np.arange(16)})
      print(df)


      Output:



           a
      0 0
      1 1
      2 2
      3 3
      4 4
      5 5
      6 6
      7 7
      8 8
      9 9
      10 10
      11 11
      12 12
      13 13
      14 14


      Expected:



           a
      2 2
      3 3
      4 4
      7 7
      8 8
      9 9
      12 12
      13 13
      14 14


      Hopefully for help!










      share|improve this question














      I want to select 3 rows every 5 rows. For example, the first 5 rows, I want to remain the last 3 rows.



      Input:



      import pandas as pd 
      df = pd.DataFrame({'a': np.arange(16)})
      print(df)


      Output:



           a
      0 0
      1 1
      2 2
      3 3
      4 4
      5 5
      6 6
      7 7
      8 8
      9 9
      10 10
      11 11
      12 12
      13 13
      14 14


      Expected:



           a
      2 2
      3 3
      4 4
      7 7
      8 8
      9 9
      12 12
      13 13
      14 14


      Hopefully for help!







      python pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 10:54









      rosefunrosefun

      415210




      415210
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Use groupby with index with floor division and get last 3 rows by tail:



          df = df.groupby(df.index // 5).tail(3)
          print(df)
          a
          2 2
          3 3
          4 4
          7 7
          8 8
          9 9
          12 12
          13 13
          14 14
          15 15 <- last group have only one value, so tail select it


          Another idea is get index values of each rows by np.arange with reshape to 2d array, select last 'columns' and flatten by ravel, get intersection with real index values and select by loc:



          N = 5
          M = 3
          pos = np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel()
          idx = np.intersect1d(df.index, pos)

          df = df.loc[idx]
          print(df)
          a
          2 2
          3 3
          4 4
          7 7
          8 8
          9 9
          12 12
          13 13
          14 14


          Detail:



          print(np.arange((len(df) // N + 1) * N).reshape(-1, N))
          [[ 0 1 2 3 4]
          [ 5 6 7 8 9]
          [10 11 12 13 14]
          [15 16 17 18 19]]

          print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:])
          [[ 2 3 4]
          [ 7 8 9]
          [12 13 14]
          [17 18 19]]

          print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel())
          [ 2 3 4 7 8 9 12 13 14 17 18 19]

          print(np.intersect1d(df.index, pos))
          [ 2 3 4 7 8 9 12 13 14]





          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%2f53457397%2fhow-to-select-several-continue-rows-with-interval-in-pandas%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Use groupby with index with floor division and get last 3 rows by tail:



            df = df.groupby(df.index // 5).tail(3)
            print(df)
            a
            2 2
            3 3
            4 4
            7 7
            8 8
            9 9
            12 12
            13 13
            14 14
            15 15 <- last group have only one value, so tail select it


            Another idea is get index values of each rows by np.arange with reshape to 2d array, select last 'columns' and flatten by ravel, get intersection with real index values and select by loc:



            N = 5
            M = 3
            pos = np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel()
            idx = np.intersect1d(df.index, pos)

            df = df.loc[idx]
            print(df)
            a
            2 2
            3 3
            4 4
            7 7
            8 8
            9 9
            12 12
            13 13
            14 14


            Detail:



            print(np.arange((len(df) // N + 1) * N).reshape(-1, N))
            [[ 0 1 2 3 4]
            [ 5 6 7 8 9]
            [10 11 12 13 14]
            [15 16 17 18 19]]

            print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:])
            [[ 2 3 4]
            [ 7 8 9]
            [12 13 14]
            [17 18 19]]

            print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel())
            [ 2 3 4 7 8 9 12 13 14 17 18 19]

            print(np.intersect1d(df.index, pos))
            [ 2 3 4 7 8 9 12 13 14]





            share|improve this answer






























              1














              Use groupby with index with floor division and get last 3 rows by tail:



              df = df.groupby(df.index // 5).tail(3)
              print(df)
              a
              2 2
              3 3
              4 4
              7 7
              8 8
              9 9
              12 12
              13 13
              14 14
              15 15 <- last group have only one value, so tail select it


              Another idea is get index values of each rows by np.arange with reshape to 2d array, select last 'columns' and flatten by ravel, get intersection with real index values and select by loc:



              N = 5
              M = 3
              pos = np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel()
              idx = np.intersect1d(df.index, pos)

              df = df.loc[idx]
              print(df)
              a
              2 2
              3 3
              4 4
              7 7
              8 8
              9 9
              12 12
              13 13
              14 14


              Detail:



              print(np.arange((len(df) // N + 1) * N).reshape(-1, N))
              [[ 0 1 2 3 4]
              [ 5 6 7 8 9]
              [10 11 12 13 14]
              [15 16 17 18 19]]

              print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:])
              [[ 2 3 4]
              [ 7 8 9]
              [12 13 14]
              [17 18 19]]

              print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel())
              [ 2 3 4 7 8 9 12 13 14 17 18 19]

              print(np.intersect1d(df.index, pos))
              [ 2 3 4 7 8 9 12 13 14]





              share|improve this answer




























                1












                1








                1







                Use groupby with index with floor division and get last 3 rows by tail:



                df = df.groupby(df.index // 5).tail(3)
                print(df)
                a
                2 2
                3 3
                4 4
                7 7
                8 8
                9 9
                12 12
                13 13
                14 14
                15 15 <- last group have only one value, so tail select it


                Another idea is get index values of each rows by np.arange with reshape to 2d array, select last 'columns' and flatten by ravel, get intersection with real index values and select by loc:



                N = 5
                M = 3
                pos = np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel()
                idx = np.intersect1d(df.index, pos)

                df = df.loc[idx]
                print(df)
                a
                2 2
                3 3
                4 4
                7 7
                8 8
                9 9
                12 12
                13 13
                14 14


                Detail:



                print(np.arange((len(df) // N + 1) * N).reshape(-1, N))
                [[ 0 1 2 3 4]
                [ 5 6 7 8 9]
                [10 11 12 13 14]
                [15 16 17 18 19]]

                print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:])
                [[ 2 3 4]
                [ 7 8 9]
                [12 13 14]
                [17 18 19]]

                print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel())
                [ 2 3 4 7 8 9 12 13 14 17 18 19]

                print(np.intersect1d(df.index, pos))
                [ 2 3 4 7 8 9 12 13 14]





                share|improve this answer















                Use groupby with index with floor division and get last 3 rows by tail:



                df = df.groupby(df.index // 5).tail(3)
                print(df)
                a
                2 2
                3 3
                4 4
                7 7
                8 8
                9 9
                12 12
                13 13
                14 14
                15 15 <- last group have only one value, so tail select it


                Another idea is get index values of each rows by np.arange with reshape to 2d array, select last 'columns' and flatten by ravel, get intersection with real index values and select by loc:



                N = 5
                M = 3
                pos = np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel()
                idx = np.intersect1d(df.index, pos)

                df = df.loc[idx]
                print(df)
                a
                2 2
                3 3
                4 4
                7 7
                8 8
                9 9
                12 12
                13 13
                14 14


                Detail:



                print(np.arange((len(df) // N + 1) * N).reshape(-1, N))
                [[ 0 1 2 3 4]
                [ 5 6 7 8 9]
                [10 11 12 13 14]
                [15 16 17 18 19]]

                print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:])
                [[ 2 3 4]
                [ 7 8 9]
                [12 13 14]
                [17 18 19]]

                print (np.arange((len(df) // N + 1) * N).reshape(-1, N)[:, -M:].ravel())
                [ 2 3 4 7 8 9 12 13 14 17 18 19]

                print(np.intersect1d(df.index, pos))
                [ 2 3 4 7 8 9 12 13 14]






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 24 '18 at 11:24

























                answered Nov 24 '18 at 10:56









                jezraeljezrael

                336k25281357




                336k25281357
































                    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%2f53457397%2fhow-to-select-several-continue-rows-with-interval-in-pandas%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

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'