get string slices in a groupby statement python











up vote
1
down vote

favorite












I have a dataframe where I want to group by the ID field and get last letters in GG field. For example, say I have the following:



df1 = pd.DataFrame({
'ID':['Q'] * 3,
'GG':['L3S_0097A','L3S_0097B','L3S_0097C']

})

print (df1)
ID GG
0 Q L3S_0097A
1 Q L3S_0097B
2 Q L3S_0097C


I am trying to groupby ID column and get only last letter in GG column and add it to the defaultdict like this:



{'Q': ['A','B','C']}


Here is the code I tried:



mm = df1.groupby('ID')['GG'].str[-1].apply(list).to_dict()
and also tried the following code:
for i, j in zip(df1.ID,df1.GG):
mm[i].append(j[-1])


but both din't work. May I know how to do it?










share|improve this question




























    up vote
    1
    down vote

    favorite












    I have a dataframe where I want to group by the ID field and get last letters in GG field. For example, say I have the following:



    df1 = pd.DataFrame({
    'ID':['Q'] * 3,
    'GG':['L3S_0097A','L3S_0097B','L3S_0097C']

    })

    print (df1)
    ID GG
    0 Q L3S_0097A
    1 Q L3S_0097B
    2 Q L3S_0097C


    I am trying to groupby ID column and get only last letter in GG column and add it to the defaultdict like this:



    {'Q': ['A','B','C']}


    Here is the code I tried:



    mm = df1.groupby('ID')['GG'].str[-1].apply(list).to_dict()
    and also tried the following code:
    for i, j in zip(df1.ID,df1.GG):
    mm[i].append(j[-1])


    but both din't work. May I know how to do it?










    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have a dataframe where I want to group by the ID field and get last letters in GG field. For example, say I have the following:



      df1 = pd.DataFrame({
      'ID':['Q'] * 3,
      'GG':['L3S_0097A','L3S_0097B','L3S_0097C']

      })

      print (df1)
      ID GG
      0 Q L3S_0097A
      1 Q L3S_0097B
      2 Q L3S_0097C


      I am trying to groupby ID column and get only last letter in GG column and add it to the defaultdict like this:



      {'Q': ['A','B','C']}


      Here is the code I tried:



      mm = df1.groupby('ID')['GG'].str[-1].apply(list).to_dict()
      and also tried the following code:
      for i, j in zip(df1.ID,df1.GG):
      mm[i].append(j[-1])


      but both din't work. May I know how to do it?










      share|improve this question















      I have a dataframe where I want to group by the ID field and get last letters in GG field. For example, say I have the following:



      df1 = pd.DataFrame({
      'ID':['Q'] * 3,
      'GG':['L3S_0097A','L3S_0097B','L3S_0097C']

      })

      print (df1)
      ID GG
      0 Q L3S_0097A
      1 Q L3S_0097B
      2 Q L3S_0097C


      I am trying to groupby ID column and get only last letter in GG column and add it to the defaultdict like this:



      {'Q': ['A','B','C']}


      Here is the code I tried:



      mm = df1.groupby('ID')['GG'].str[-1].apply(list).to_dict()
      and also tried the following code:
      for i, j in zip(df1.ID,df1.GG):
      mm[i].append(j[-1])


      but both din't work. May I know how to do it?







      python-3.x pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 12:01









      jezrael

      316k22256333




      316k22256333










      asked Nov 20 at 11:53









      amrutha

      827




      827
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote













          Use syntactic sugar - groupby by - 2 Series - GG Series with last value and df1['ID']:



          mm = df1['GG'].str[-1].groupby(df1['ID']).apply(list).to_dict()


          Or assign only last value back to GG:



          mm = df1.assign(GG = df1['GG'].str[-1]).groupby('ID')['GG'].apply(list).to_dict()




          print (mm)
          {'Q': ['A', 'B', 'C']}


          Pure python solution:



          from collections import defaultdict

          mm = defaultdict(list)
          #https://stackoverflow.com/a/10532492
          for i, j in zip(df1.ID,df1.GG):
          mm[i].append(j[-1])

          print (mm)
          defaultdict(<class 'list'>, {'Q': ['A', 'B', 'C']})





          share|improve this answer























          • thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
            – amrutha
            Nov 20 at 12:07












          • @amrutha - I think need defaultdict for this.
            – jezrael
            Nov 20 at 12:14











          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%2f53392451%2fget-string-slices-in-a-groupby-statement-python%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








          up vote
          1
          down vote













          Use syntactic sugar - groupby by - 2 Series - GG Series with last value and df1['ID']:



          mm = df1['GG'].str[-1].groupby(df1['ID']).apply(list).to_dict()


          Or assign only last value back to GG:



          mm = df1.assign(GG = df1['GG'].str[-1]).groupby('ID')['GG'].apply(list).to_dict()




          print (mm)
          {'Q': ['A', 'B', 'C']}


          Pure python solution:



          from collections import defaultdict

          mm = defaultdict(list)
          #https://stackoverflow.com/a/10532492
          for i, j in zip(df1.ID,df1.GG):
          mm[i].append(j[-1])

          print (mm)
          defaultdict(<class 'list'>, {'Q': ['A', 'B', 'C']})





          share|improve this answer























          • thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
            – amrutha
            Nov 20 at 12:07












          • @amrutha - I think need defaultdict for this.
            – jezrael
            Nov 20 at 12:14















          up vote
          1
          down vote













          Use syntactic sugar - groupby by - 2 Series - GG Series with last value and df1['ID']:



          mm = df1['GG'].str[-1].groupby(df1['ID']).apply(list).to_dict()


          Or assign only last value back to GG:



          mm = df1.assign(GG = df1['GG'].str[-1]).groupby('ID')['GG'].apply(list).to_dict()




          print (mm)
          {'Q': ['A', 'B', 'C']}


          Pure python solution:



          from collections import defaultdict

          mm = defaultdict(list)
          #https://stackoverflow.com/a/10532492
          for i, j in zip(df1.ID,df1.GG):
          mm[i].append(j[-1])

          print (mm)
          defaultdict(<class 'list'>, {'Q': ['A', 'B', 'C']})





          share|improve this answer























          • thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
            – amrutha
            Nov 20 at 12:07












          • @amrutha - I think need defaultdict for this.
            – jezrael
            Nov 20 at 12:14













          up vote
          1
          down vote










          up vote
          1
          down vote









          Use syntactic sugar - groupby by - 2 Series - GG Series with last value and df1['ID']:



          mm = df1['GG'].str[-1].groupby(df1['ID']).apply(list).to_dict()


          Or assign only last value back to GG:



          mm = df1.assign(GG = df1['GG'].str[-1]).groupby('ID')['GG'].apply(list).to_dict()




          print (mm)
          {'Q': ['A', 'B', 'C']}


          Pure python solution:



          from collections import defaultdict

          mm = defaultdict(list)
          #https://stackoverflow.com/a/10532492
          for i, j in zip(df1.ID,df1.GG):
          mm[i].append(j[-1])

          print (mm)
          defaultdict(<class 'list'>, {'Q': ['A', 'B', 'C']})





          share|improve this answer














          Use syntactic sugar - groupby by - 2 Series - GG Series with last value and df1['ID']:



          mm = df1['GG'].str[-1].groupby(df1['ID']).apply(list).to_dict()


          Or assign only last value back to GG:



          mm = df1.assign(GG = df1['GG'].str[-1]).groupby('ID')['GG'].apply(list).to_dict()




          print (mm)
          {'Q': ['A', 'B', 'C']}


          Pure python solution:



          from collections import defaultdict

          mm = defaultdict(list)
          #https://stackoverflow.com/a/10532492
          for i, j in zip(df1.ID,df1.GG):
          mm[i].append(j[-1])

          print (mm)
          defaultdict(<class 'list'>, {'Q': ['A', 'B', 'C']})






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 at 12:14

























          answered Nov 20 at 11:56









          jezrael

          316k22256333




          316k22256333












          • thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
            – amrutha
            Nov 20 at 12:07












          • @amrutha - I think need defaultdict for this.
            – jezrael
            Nov 20 at 12:14


















          • thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
            – amrutha
            Nov 20 at 12:07












          • @amrutha - I think need defaultdict for this.
            – jezrael
            Nov 20 at 12:14
















          thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
          – amrutha
          Nov 20 at 12:07






          thanks.. it worked.. but may I know how can I do it with zip statement? because when I tried using the above posted zip code, I get the error like this: "AttributeError: 'list' object has no attribute 'str' "
          – amrutha
          Nov 20 at 12:07














          @amrutha - I think need defaultdict for this.
          – jezrael
          Nov 20 at 12:14




          @amrutha - I think need defaultdict for this.
          – jezrael
          Nov 20 at 12:14


















          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%2f53392451%2fget-string-slices-in-a-groupby-statement-python%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

          Wiesbaden

          Marschland

          Dieringhausen