Changing a column value in pandas dataframe excluding the tail in group by












2














Let's take an example of a python dataframe.



ID Age Bp



1 22 1



1 22 1



1 22 0



1 22 1



2 21 0



2 21 1



2 21 0



In the above code, the last n series for column BP (lets consider n to be 2) with group by ID should be excluded and the rest of the BP should be changed to 0. I have tried it with tail but it does not work.



It should look like this.



ID Age BP



1 22 0



1 22 0



1 22 0



1 22 1



2 21 0



2 21 1



2 21 0










share|improve this question



























    2














    Let's take an example of a python dataframe.



    ID Age Bp



    1 22 1



    1 22 1



    1 22 0



    1 22 1



    2 21 0



    2 21 1



    2 21 0



    In the above code, the last n series for column BP (lets consider n to be 2) with group by ID should be excluded and the rest of the BP should be changed to 0. I have tried it with tail but it does not work.



    It should look like this.



    ID Age BP



    1 22 0



    1 22 0



    1 22 0



    1 22 1



    2 21 0



    2 21 1



    2 21 0










    share|improve this question

























      2












      2








      2







      Let's take an example of a python dataframe.



      ID Age Bp



      1 22 1



      1 22 1



      1 22 0



      1 22 1



      2 21 0



      2 21 1



      2 21 0



      In the above code, the last n series for column BP (lets consider n to be 2) with group by ID should be excluded and the rest of the BP should be changed to 0. I have tried it with tail but it does not work.



      It should look like this.



      ID Age BP



      1 22 0



      1 22 0



      1 22 0



      1 22 1



      2 21 0



      2 21 1



      2 21 0










      share|improve this question













      Let's take an example of a python dataframe.



      ID Age Bp



      1 22 1



      1 22 1



      1 22 0



      1 22 1



      2 21 0



      2 21 1



      2 21 0



      In the above code, the last n series for column BP (lets consider n to be 2) with group by ID should be excluded and the rest of the BP should be changed to 0. I have tried it with tail but it does not work.



      It should look like this.



      ID Age BP



      1 22 0



      1 22 0



      1 22 0



      1 22 1



      2 21 0



      2 21 1



      2 21 0







      python pandas






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 17:57









      user123

      185




      185
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Use cumcount with ascending=False for counter from back per groups and assign 0 with numpy.where:



          n = 2
          mask = df.groupby('ID').cumcount(ascending=False) < n
          df['Bp'] = np.where(mask, df['Bp'], 0)


          Alternatives:



          df.loc[~mask, 'Bp'] = 0
          df['Bp'] = df['Bp'].where(mask, 0)




          print (df)
          ID Age Bp
          0 1 22 0
          1 1 22 0
          2 1 22 0
          3 1 22 1
          4 2 21 0
          5 2 21 1
          6 2 21 0


          Details:



          print (df.groupby('ID').cumcount(ascending=False))
          0 3
          1 2
          2 1
          3 0
          4 2
          5 1
          6 0
          dtype: int64

          print (mask)
          0 False
          1 False
          2 True
          3 True
          4 False
          5 True
          6 True
          dtype: bool





          share|improve this answer





















          • Thanks for the help it worked
            – user123
            Nov 10 at 19:30










          • @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
            – jezrael
            Nov 10 at 19:30











          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%2f53241848%2fchanging-a-column-value-in-pandas-dataframe-excluding-the-tail-in-group-by%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









          2














          Use cumcount with ascending=False for counter from back per groups and assign 0 with numpy.where:



          n = 2
          mask = df.groupby('ID').cumcount(ascending=False) < n
          df['Bp'] = np.where(mask, df['Bp'], 0)


          Alternatives:



          df.loc[~mask, 'Bp'] = 0
          df['Bp'] = df['Bp'].where(mask, 0)




          print (df)
          ID Age Bp
          0 1 22 0
          1 1 22 0
          2 1 22 0
          3 1 22 1
          4 2 21 0
          5 2 21 1
          6 2 21 0


          Details:



          print (df.groupby('ID').cumcount(ascending=False))
          0 3
          1 2
          2 1
          3 0
          4 2
          5 1
          6 0
          dtype: int64

          print (mask)
          0 False
          1 False
          2 True
          3 True
          4 False
          5 True
          6 True
          dtype: bool





          share|improve this answer





















          • Thanks for the help it worked
            – user123
            Nov 10 at 19:30










          • @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
            – jezrael
            Nov 10 at 19:30
















          2














          Use cumcount with ascending=False for counter from back per groups and assign 0 with numpy.where:



          n = 2
          mask = df.groupby('ID').cumcount(ascending=False) < n
          df['Bp'] = np.where(mask, df['Bp'], 0)


          Alternatives:



          df.loc[~mask, 'Bp'] = 0
          df['Bp'] = df['Bp'].where(mask, 0)




          print (df)
          ID Age Bp
          0 1 22 0
          1 1 22 0
          2 1 22 0
          3 1 22 1
          4 2 21 0
          5 2 21 1
          6 2 21 0


          Details:



          print (df.groupby('ID').cumcount(ascending=False))
          0 3
          1 2
          2 1
          3 0
          4 2
          5 1
          6 0
          dtype: int64

          print (mask)
          0 False
          1 False
          2 True
          3 True
          4 False
          5 True
          6 True
          dtype: bool





          share|improve this answer





















          • Thanks for the help it worked
            – user123
            Nov 10 at 19:30










          • @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
            – jezrael
            Nov 10 at 19:30














          2












          2








          2






          Use cumcount with ascending=False for counter from back per groups and assign 0 with numpy.where:



          n = 2
          mask = df.groupby('ID').cumcount(ascending=False) < n
          df['Bp'] = np.where(mask, df['Bp'], 0)


          Alternatives:



          df.loc[~mask, 'Bp'] = 0
          df['Bp'] = df['Bp'].where(mask, 0)




          print (df)
          ID Age Bp
          0 1 22 0
          1 1 22 0
          2 1 22 0
          3 1 22 1
          4 2 21 0
          5 2 21 1
          6 2 21 0


          Details:



          print (df.groupby('ID').cumcount(ascending=False))
          0 3
          1 2
          2 1
          3 0
          4 2
          5 1
          6 0
          dtype: int64

          print (mask)
          0 False
          1 False
          2 True
          3 True
          4 False
          5 True
          6 True
          dtype: bool





          share|improve this answer












          Use cumcount with ascending=False for counter from back per groups and assign 0 with numpy.where:



          n = 2
          mask = df.groupby('ID').cumcount(ascending=False) < n
          df['Bp'] = np.where(mask, df['Bp'], 0)


          Alternatives:



          df.loc[~mask, 'Bp'] = 0
          df['Bp'] = df['Bp'].where(mask, 0)




          print (df)
          ID Age Bp
          0 1 22 0
          1 1 22 0
          2 1 22 0
          3 1 22 1
          4 2 21 0
          5 2 21 1
          6 2 21 0


          Details:



          print (df.groupby('ID').cumcount(ascending=False))
          0 3
          1 2
          2 1
          3 0
          4 2
          5 1
          6 0
          dtype: int64

          print (mask)
          0 False
          1 False
          2 True
          3 True
          4 False
          5 True
          6 True
          dtype: bool






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 18:36









          jezrael

          318k22257336




          318k22257336












          • Thanks for the help it worked
            – user123
            Nov 10 at 19:30










          • @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
            – jezrael
            Nov 10 at 19:30


















          • Thanks for the help it worked
            – user123
            Nov 10 at 19:30










          • @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
            – jezrael
            Nov 10 at 19:30
















          Thanks for the help it worked
          – user123
          Nov 10 at 19:30




          Thanks for the help it worked
          – user123
          Nov 10 at 19:30












          @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
          – jezrael
          Nov 10 at 19:30




          @user123 - You are welcome! If my answer was helpful, don't forget accept it. To mark an answer as accepted, click on the check mark beside the answer to toggle it from hollow to green (see screenshot). Thank you.
          – jezrael
          Nov 10 at 19:30


















          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%2f53241848%2fchanging-a-column-value-in-pandas-dataframe-excluding-the-tail-in-group-by%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







          這個網誌中的熱門文章

          Xamarin.form Move up view when keyboard appear

          Post-Redirect-Get with Spring WebFlux and Thymeleaf

          Anylogic : not able to use stopDelay()