Pandas: Modify a particular level of Multiindex, using replace method several times











up vote
2
down vote

favorite












I am trying to use the replace method several times in order to change the indeces of a given level of a multiindex pandas' dataframe.



As seen here: Pandas: Modify a particular level of Multiindex, @John got a solution that works great so long the replace method is used once.



The problem is, that it does not work if I use this method several times.
E.g.



df.index = df.index.set_levels(df.index.levels[0].str.replace("dataframe_",'').replace("_r",' r'), level=0)


I get the following error message:



AttributeError: 'Index' object has no attribute 'replace'


What am I missing?










share|improve this question


























    up vote
    2
    down vote

    favorite












    I am trying to use the replace method several times in order to change the indeces of a given level of a multiindex pandas' dataframe.



    As seen here: Pandas: Modify a particular level of Multiindex, @John got a solution that works great so long the replace method is used once.



    The problem is, that it does not work if I use this method several times.
    E.g.



    df.index = df.index.set_levels(df.index.levels[0].str.replace("dataframe_",'').replace("_r",' r'), level=0)


    I get the following error message:



    AttributeError: 'Index' object has no attribute 'replace'


    What am I missing?










    share|improve this question
























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I am trying to use the replace method several times in order to change the indeces of a given level of a multiindex pandas' dataframe.



      As seen here: Pandas: Modify a particular level of Multiindex, @John got a solution that works great so long the replace method is used once.



      The problem is, that it does not work if I use this method several times.
      E.g.



      df.index = df.index.set_levels(df.index.levels[0].str.replace("dataframe_",'').replace("_r",' r'), level=0)


      I get the following error message:



      AttributeError: 'Index' object has no attribute 'replace'


      What am I missing?










      share|improve this question













      I am trying to use the replace method several times in order to change the indeces of a given level of a multiindex pandas' dataframe.



      As seen here: Pandas: Modify a particular level of Multiindex, @John got a solution that works great so long the replace method is used once.



      The problem is, that it does not work if I use this method several times.
      E.g.



      df.index = df.index.set_levels(df.index.levels[0].str.replace("dataframe_",'').replace("_r",' r'), level=0)


      I get the following error message:



      AttributeError: 'Index' object has no attribute 'replace'


      What am I missing?







      python pandas dataframe multi-index






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 9:20









      rubebop

      185




      185
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          Use str.replace twice:



          idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
          df.index = df.index.set_levels(idx, level=0)


          Another solution is converting to_series and then replace by dictionary:



          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)


          And solution with map and fillna, if large data and performance is important:



          d = {'dataframe_':'','_r':' r'}
          s = df.index.levels[0].to_series()
          df.index = df.index.set_levels(s.map(d).fillna(s), level=0)




          Sample:



          df = pd.DataFrame({
          'A':['dataframe_','_r', 'a'],
          'B':[7,8,9],
          'C':[1,3,5],

          }).set_index(['A','B'])

          print (df)
          C
          A B
          dataframe_ 7 1
          _r 8 3
          a 9 5

          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)
          print (df)
          C
          A B
          7 1
          r 8 3
          a 9 5





          share|improve this answer























          • Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
            – rubebop
            Nov 8 at 15:43












          • @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
            – jezrael
            2 days ago






          • 1




            I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
            – rubebop
            2 days ago













          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%2f53204697%2fpandas-modify-a-particular-level-of-multiindex-using-replace-method-several-ti%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          Use str.replace twice:



          idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
          df.index = df.index.set_levels(idx, level=0)


          Another solution is converting to_series and then replace by dictionary:



          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)


          And solution with map and fillna, if large data and performance is important:



          d = {'dataframe_':'','_r':' r'}
          s = df.index.levels[0].to_series()
          df.index = df.index.set_levels(s.map(d).fillna(s), level=0)




          Sample:



          df = pd.DataFrame({
          'A':['dataframe_','_r', 'a'],
          'B':[7,8,9],
          'C':[1,3,5],

          }).set_index(['A','B'])

          print (df)
          C
          A B
          dataframe_ 7 1
          _r 8 3
          a 9 5

          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)
          print (df)
          C
          A B
          7 1
          r 8 3
          a 9 5





          share|improve this answer























          • Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
            – rubebop
            Nov 8 at 15:43












          • @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
            – jezrael
            2 days ago






          • 1




            I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
            – rubebop
            2 days ago

















          up vote
          2
          down vote



          accepted










          Use str.replace twice:



          idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
          df.index = df.index.set_levels(idx, level=0)


          Another solution is converting to_series and then replace by dictionary:



          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)


          And solution with map and fillna, if large data and performance is important:



          d = {'dataframe_':'','_r':' r'}
          s = df.index.levels[0].to_series()
          df.index = df.index.set_levels(s.map(d).fillna(s), level=0)




          Sample:



          df = pd.DataFrame({
          'A':['dataframe_','_r', 'a'],
          'B':[7,8,9],
          'C':[1,3,5],

          }).set_index(['A','B'])

          print (df)
          C
          A B
          dataframe_ 7 1
          _r 8 3
          a 9 5

          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)
          print (df)
          C
          A B
          7 1
          r 8 3
          a 9 5





          share|improve this answer























          • Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
            – rubebop
            Nov 8 at 15:43












          • @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
            – jezrael
            2 days ago






          • 1




            I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
            – rubebop
            2 days ago















          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          Use str.replace twice:



          idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
          df.index = df.index.set_levels(idx, level=0)


          Another solution is converting to_series and then replace by dictionary:



          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)


          And solution with map and fillna, if large data and performance is important:



          d = {'dataframe_':'','_r':' r'}
          s = df.index.levels[0].to_series()
          df.index = df.index.set_levels(s.map(d).fillna(s), level=0)




          Sample:



          df = pd.DataFrame({
          'A':['dataframe_','_r', 'a'],
          'B':[7,8,9],
          'C':[1,3,5],

          }).set_index(['A','B'])

          print (df)
          C
          A B
          dataframe_ 7 1
          _r 8 3
          a 9 5

          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)
          print (df)
          C
          A B
          7 1
          r 8 3
          a 9 5





          share|improve this answer














          Use str.replace twice:



          idx = df.index.levels[0].str.replace("dataframe_",'').str.replace("_r",' r')
          df.index = df.index.set_levels(idx, level=0)


          Another solution is converting to_series and then replace by dictionary:



          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)


          And solution with map and fillna, if large data and performance is important:



          d = {'dataframe_':'','_r':' r'}
          s = df.index.levels[0].to_series()
          df.index = df.index.set_levels(s.map(d).fillna(s), level=0)




          Sample:



          df = pd.DataFrame({
          'A':['dataframe_','_r', 'a'],
          'B':[7,8,9],
          'C':[1,3,5],

          }).set_index(['A','B'])

          print (df)
          C
          A B
          dataframe_ 7 1
          _r 8 3
          a 9 5

          d = {'dataframe_':'','_r':' r'}
          idx = df.index.levels[0].to_series().replace(d)
          df.index = df.index.set_levels(idx, level=0)
          print (df)
          C
          A B
          7 1
          r 8 3
          a 9 5






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 8 at 9:40

























          answered Nov 8 at 9:21









          jezrael

          304k20237314




          304k20237314












          • Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
            – rubebop
            Nov 8 at 15:43












          • @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
            – jezrael
            2 days ago






          • 1




            I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
            – rubebop
            2 days ago




















          • Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
            – rubebop
            Nov 8 at 15:43












          • @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
            – jezrael
            2 days ago






          • 1




            I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
            – rubebop
            2 days ago


















          Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
          – rubebop
          Nov 8 at 15:43






          Thanks a lot for your great and extensive answer! A learnt very useful stuff, and pardon my stupid initial question, as I missed that ".str" before the second replace method.
          – rubebop
          Nov 8 at 15:43














          @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
          – jezrael
          2 days ago




          @rubebop - You are welcome! If my answer was helpful, don't forget accept it - click on the check mark beside the answer to toggle it from greyed out to filled in. Thanks.
          – jezrael
          2 days ago




          1




          1




          I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
          – rubebop
          2 days ago






          I accepted it: sorry, I am rather new at this and was not aware about this feature. Thanks again! :)
          – rubebop
          2 days ago




















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53204697%2fpandas-modify-a-particular-level-of-multiindex-using-replace-method-several-ti%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)