Find the row associated with maximum date after groupby in Pandas











up vote
2
down vote

favorite












I have a pandas DataFrame with 3 columns containing a PERSON_ID, MOVING_DATE AND PLACE as follows:



df = pandas.DataFrame(
[[1,datetime.datetime(2018, 1, 1), 'New York'],
[1, datetime.datetime(2018, 1, 20), 'Rio de Janeiro'],
[1, datetime.datetime(2018, 2, 13), 'London'],
[2, datetime.datetime(2017, 6, 12), 'Seatle'],
[2, datetime.datetime(2016, 10, 10), 'New Mexico'],
[3, datetime.datetime(2017, 9, 19), 'Sao Paulo'],
[3, datetime.datetime(2015, 12, 11), 'Bangladesh']]],
columns=['PERSON ID', 'MOVING DATE', 'PLACE']
)

PERSON ID MOVING DATE PLACE
0 1 2018-01-01 New York
1 1 2018-01-20 Rio de Janeiro
2 1 2018-02-13 London
3 2 2017-06-12 Seatle
4 2 2016-10-10 New Mexico
5 3 2017-09-19 Sao Paulo
6 3 2015-12-11 Bangladesh


I would like to find the place where the person is based on its last movement date (MOVEMENT_DATE).



Is it possible to get the result with the groupby method?



So far, I've tried:



df = df.sort_values(['PERSON ID', 'MOVING DATE'])
df.groupby(['PERSON ID', 'MOVING DATE']).agg(
{'MOVING DATE': max, 'PLACE': 'last'}
)


but it didn't work out.
Any help would be appreciated.



Thanks in advance,



Rhenan










share|improve this question




























    up vote
    2
    down vote

    favorite












    I have a pandas DataFrame with 3 columns containing a PERSON_ID, MOVING_DATE AND PLACE as follows:



    df = pandas.DataFrame(
    [[1,datetime.datetime(2018, 1, 1), 'New York'],
    [1, datetime.datetime(2018, 1, 20), 'Rio de Janeiro'],
    [1, datetime.datetime(2018, 2, 13), 'London'],
    [2, datetime.datetime(2017, 6, 12), 'Seatle'],
    [2, datetime.datetime(2016, 10, 10), 'New Mexico'],
    [3, datetime.datetime(2017, 9, 19), 'Sao Paulo'],
    [3, datetime.datetime(2015, 12, 11), 'Bangladesh']]],
    columns=['PERSON ID', 'MOVING DATE', 'PLACE']
    )

    PERSON ID MOVING DATE PLACE
    0 1 2018-01-01 New York
    1 1 2018-01-20 Rio de Janeiro
    2 1 2018-02-13 London
    3 2 2017-06-12 Seatle
    4 2 2016-10-10 New Mexico
    5 3 2017-09-19 Sao Paulo
    6 3 2015-12-11 Bangladesh


    I would like to find the place where the person is based on its last movement date (MOVEMENT_DATE).



    Is it possible to get the result with the groupby method?



    So far, I've tried:



    df = df.sort_values(['PERSON ID', 'MOVING DATE'])
    df.groupby(['PERSON ID', 'MOVING DATE']).agg(
    {'MOVING DATE': max, 'PLACE': 'last'}
    )


    but it didn't work out.
    Any help would be appreciated.



    Thanks in advance,



    Rhenan










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I have a pandas DataFrame with 3 columns containing a PERSON_ID, MOVING_DATE AND PLACE as follows:



      df = pandas.DataFrame(
      [[1,datetime.datetime(2018, 1, 1), 'New York'],
      [1, datetime.datetime(2018, 1, 20), 'Rio de Janeiro'],
      [1, datetime.datetime(2018, 2, 13), 'London'],
      [2, datetime.datetime(2017, 6, 12), 'Seatle'],
      [2, datetime.datetime(2016, 10, 10), 'New Mexico'],
      [3, datetime.datetime(2017, 9, 19), 'Sao Paulo'],
      [3, datetime.datetime(2015, 12, 11), 'Bangladesh']]],
      columns=['PERSON ID', 'MOVING DATE', 'PLACE']
      )

      PERSON ID MOVING DATE PLACE
      0 1 2018-01-01 New York
      1 1 2018-01-20 Rio de Janeiro
      2 1 2018-02-13 London
      3 2 2017-06-12 Seatle
      4 2 2016-10-10 New Mexico
      5 3 2017-09-19 Sao Paulo
      6 3 2015-12-11 Bangladesh


      I would like to find the place where the person is based on its last movement date (MOVEMENT_DATE).



      Is it possible to get the result with the groupby method?



      So far, I've tried:



      df = df.sort_values(['PERSON ID', 'MOVING DATE'])
      df.groupby(['PERSON ID', 'MOVING DATE']).agg(
      {'MOVING DATE': max, 'PLACE': 'last'}
      )


      but it didn't work out.
      Any help would be appreciated.



      Thanks in advance,



      Rhenan










      share|improve this question















      I have a pandas DataFrame with 3 columns containing a PERSON_ID, MOVING_DATE AND PLACE as follows:



      df = pandas.DataFrame(
      [[1,datetime.datetime(2018, 1, 1), 'New York'],
      [1, datetime.datetime(2018, 1, 20), 'Rio de Janeiro'],
      [1, datetime.datetime(2018, 2, 13), 'London'],
      [2, datetime.datetime(2017, 6, 12), 'Seatle'],
      [2, datetime.datetime(2016, 10, 10), 'New Mexico'],
      [3, datetime.datetime(2017, 9, 19), 'Sao Paulo'],
      [3, datetime.datetime(2015, 12, 11), 'Bangladesh']]],
      columns=['PERSON ID', 'MOVING DATE', 'PLACE']
      )

      PERSON ID MOVING DATE PLACE
      0 1 2018-01-01 New York
      1 1 2018-01-20 Rio de Janeiro
      2 1 2018-02-13 London
      3 2 2017-06-12 Seatle
      4 2 2016-10-10 New Mexico
      5 3 2017-09-19 Sao Paulo
      6 3 2015-12-11 Bangladesh


      I would like to find the place where the person is based on its last movement date (MOVEMENT_DATE).



      Is it possible to get the result with the groupby method?



      So far, I've tried:



      df = df.sort_values(['PERSON ID', 'MOVING DATE'])
      df.groupby(['PERSON ID', 'MOVING DATE']).agg(
      {'MOVING DATE': max, 'PLACE': 'last'}
      )


      but it didn't work out.
      Any help would be appreciated.



      Thanks in advance,



      Rhenan







      python pandas pandas-groupby






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 20:10

























      asked Nov 9 at 19:37









      Rhenan Bartels

      131110




      131110
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          5
          down vote



          accepted










          A one-liner using DataFrame.groupby and Grouper.last:



          df.sort_values('MOVING DATE').groupby('PERSON ID').last()


          output:



               MOVING DATE      PLACE
          PERSON ID
          1 2018-02-13 London
          2 2017-06-12 Seatle
          3 2017-09-19 Sao Paulo





          share|improve this answer



















          • 1




            Great answer @Yuca. Thanks!!
            – Rhenan Bartels
            Nov 9 at 20:07


















          up vote
          2
          down vote













          A sort is overkill here, that's O(nlogn) time complexity, when you can do this with loc and idxmax:



          df.loc[df.groupby('PERSON ID')['MOVING DATE'].idxmax()]




             PERSON ID MOVING DATE      PLACE
          2 1 2018-02-13 London
          3 2 2017-06-12 Seatle
          5 3 2017-09-19 Sao Paulo





          share|improve this answer




























            up vote
            1
            down vote













            To add to @Yuca and the answer provided, you could also utilize the .max() function provided within the pandas lib in the same way .last() was added.



            more: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html






            share|improve this answer

















            • 1




              Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
              – Rhenan Bartels
              Nov 9 at 20:12













            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',
            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%2f53232258%2ffind-the-row-associated-with-maximum-date-after-groupby-in-pandas%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            5
            down vote



            accepted










            A one-liner using DataFrame.groupby and Grouper.last:



            df.sort_values('MOVING DATE').groupby('PERSON ID').last()


            output:



                 MOVING DATE      PLACE
            PERSON ID
            1 2018-02-13 London
            2 2017-06-12 Seatle
            3 2017-09-19 Sao Paulo





            share|improve this answer



















            • 1




              Great answer @Yuca. Thanks!!
              – Rhenan Bartels
              Nov 9 at 20:07















            up vote
            5
            down vote



            accepted










            A one-liner using DataFrame.groupby and Grouper.last:



            df.sort_values('MOVING DATE').groupby('PERSON ID').last()


            output:



                 MOVING DATE      PLACE
            PERSON ID
            1 2018-02-13 London
            2 2017-06-12 Seatle
            3 2017-09-19 Sao Paulo





            share|improve this answer



















            • 1




              Great answer @Yuca. Thanks!!
              – Rhenan Bartels
              Nov 9 at 20:07













            up vote
            5
            down vote



            accepted







            up vote
            5
            down vote



            accepted






            A one-liner using DataFrame.groupby and Grouper.last:



            df.sort_values('MOVING DATE').groupby('PERSON ID').last()


            output:



                 MOVING DATE      PLACE
            PERSON ID
            1 2018-02-13 London
            2 2017-06-12 Seatle
            3 2017-09-19 Sao Paulo





            share|improve this answer














            A one-liner using DataFrame.groupby and Grouper.last:



            df.sort_values('MOVING DATE').groupby('PERSON ID').last()


            output:



                 MOVING DATE      PLACE
            PERSON ID
            1 2018-02-13 London
            2 2017-06-12 Seatle
            3 2017-09-19 Sao Paulo






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 9 at 19:57

























            answered Nov 9 at 19:45









            Yuca

            2,5542525




            2,5542525








            • 1




              Great answer @Yuca. Thanks!!
              – Rhenan Bartels
              Nov 9 at 20:07














            • 1




              Great answer @Yuca. Thanks!!
              – Rhenan Bartels
              Nov 9 at 20:07








            1




            1




            Great answer @Yuca. Thanks!!
            – Rhenan Bartels
            Nov 9 at 20:07




            Great answer @Yuca. Thanks!!
            – Rhenan Bartels
            Nov 9 at 20:07












            up vote
            2
            down vote













            A sort is overkill here, that's O(nlogn) time complexity, when you can do this with loc and idxmax:



            df.loc[df.groupby('PERSON ID')['MOVING DATE'].idxmax()]




               PERSON ID MOVING DATE      PLACE
            2 1 2018-02-13 London
            3 2 2017-06-12 Seatle
            5 3 2017-09-19 Sao Paulo





            share|improve this answer

























              up vote
              2
              down vote













              A sort is overkill here, that's O(nlogn) time complexity, when you can do this with loc and idxmax:



              df.loc[df.groupby('PERSON ID')['MOVING DATE'].idxmax()]




                 PERSON ID MOVING DATE      PLACE
              2 1 2018-02-13 London
              3 2 2017-06-12 Seatle
              5 3 2017-09-19 Sao Paulo





              share|improve this answer























                up vote
                2
                down vote










                up vote
                2
                down vote









                A sort is overkill here, that's O(nlogn) time complexity, when you can do this with loc and idxmax:



                df.loc[df.groupby('PERSON ID')['MOVING DATE'].idxmax()]




                   PERSON ID MOVING DATE      PLACE
                2 1 2018-02-13 London
                3 2 2017-06-12 Seatle
                5 3 2017-09-19 Sao Paulo





                share|improve this answer












                A sort is overkill here, that's O(nlogn) time complexity, when you can do this with loc and idxmax:



                df.loc[df.groupby('PERSON ID')['MOVING DATE'].idxmax()]




                   PERSON ID MOVING DATE      PLACE
                2 1 2018-02-13 London
                3 2 2017-06-12 Seatle
                5 3 2017-09-19 Sao Paulo






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 20:50









                user3483203

                29.9k82354




                29.9k82354






















                    up vote
                    1
                    down vote













                    To add to @Yuca and the answer provided, you could also utilize the .max() function provided within the pandas lib in the same way .last() was added.



                    more: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html






                    share|improve this answer

















                    • 1




                      Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                      – Rhenan Bartels
                      Nov 9 at 20:12

















                    up vote
                    1
                    down vote













                    To add to @Yuca and the answer provided, you could also utilize the .max() function provided within the pandas lib in the same way .last() was added.



                    more: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html






                    share|improve this answer

















                    • 1




                      Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                      – Rhenan Bartels
                      Nov 9 at 20:12















                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    To add to @Yuca and the answer provided, you could also utilize the .max() function provided within the pandas lib in the same way .last() was added.



                    more: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html






                    share|improve this answer












                    To add to @Yuca and the answer provided, you could also utilize the .max() function provided within the pandas lib in the same way .last() was added.



                    more: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 9 at 19:57









                    Tyler Filko

                    436




                    436








                    • 1




                      Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                      – Rhenan Bartels
                      Nov 9 at 20:12
















                    • 1




                      Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                      – Rhenan Bartels
                      Nov 9 at 20:12










                    1




                    1




                    Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                    – Rhenan Bartels
                    Nov 9 at 20:12






                    Hi @Tyler Filko, thanks for the answer, but the .max() method will use the letters of the place's name to select the maximum place, won't it?
                    – Rhenan Bartels
                    Nov 9 at 20:12




















                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53232258%2ffind-the-row-associated-with-maximum-date-after-groupby-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







                    這個網誌中的熱門文章

                    Academy of Television Arts & Sciences

                    L'Équipe

                    1995 France bombings