Pandas reindex a MultiIndex dataframe












2















is there a way to reindex two dataframes (of differing levels) so that they share a common index across all levels?



Demo:



Create a basic Dataframe named 'A':



index = np.array(['AUD','BRL','CAD','EUR','INR'])
data = np.random.randint(1, 20, (5,5))
A = pd.DataFrame(data=data, index=index, columns=index)


Create a MultiIndex Dataframe named 'B':



np.random.seed(42)
midx1 = pd.MultiIndex.from_product([['Bank_1', 'Bank_2'],
['AUD','CAD','EUR']], names=['Bank', 'Curency'])
B = pd.DataFrame(np.random.randint(10,25,6), midx1)
B.columns = ['Notional']


Basic DF:



>>> Dataframe A:

AUD BRL CAD EUR INR
AUD 7 19 11 11 4
BRL 8 3 2 12 6
CAD 2 1 12 12 17
EUR 10 16 15 15 19
INR 12 3 5 19 7


MultiIndex DF:



>>> Dataframe B:

Notional
Bank Curency
Bank_1 AUD 16
CAD 13
EUR 22
Bank_2 AUD 24
CAD 20
EUR 17


The goal is to:



1) reindex B so that its currency level includes each currency in A's index. B would then look like this (see BRL and INR included, their Notional values are not important):



                    Notional
Bank Curency
Bank_1 AUD 16
CAD 13
EUR 22
BRL 0
INR 0
Bank_2 AUD 24
CAD 20
EUR 17
BRL 0
INR 0


2) reindex A so that it includes each Bank from the first level of B's index. A would then look like this:



               AUD      BRL     CAD     EUR     INR
Bank_1 AUD 7 19 11 11 4
BRL 8 3 2 12 6
CAD 2 1 12 12 17
EUR 10 16 15 15 19
INR 12 3 5 19 7
Bank_2 AUD 7 19 11 11 4
BRL 8 3 2 12 6
CAD 2 1 12 12 17
EUR 10 16 15 15 19
INR 12 3 5 19 7


The application of this will be on much larger dataframes so I need a pythonic way to do this.



For context, ultimately I want to multiply A and B. I am trying to reindex to get matching indices as that was shown as a clean way to multiply dataframes of various index levels here:
Pandas multiply dataframes with multiindex and overlapping index levels



Thank you for any help.










share|improve this question



























    2















    is there a way to reindex two dataframes (of differing levels) so that they share a common index across all levels?



    Demo:



    Create a basic Dataframe named 'A':



    index = np.array(['AUD','BRL','CAD','EUR','INR'])
    data = np.random.randint(1, 20, (5,5))
    A = pd.DataFrame(data=data, index=index, columns=index)


    Create a MultiIndex Dataframe named 'B':



    np.random.seed(42)
    midx1 = pd.MultiIndex.from_product([['Bank_1', 'Bank_2'],
    ['AUD','CAD','EUR']], names=['Bank', 'Curency'])
    B = pd.DataFrame(np.random.randint(10,25,6), midx1)
    B.columns = ['Notional']


    Basic DF:



    >>> Dataframe A:

    AUD BRL CAD EUR INR
    AUD 7 19 11 11 4
    BRL 8 3 2 12 6
    CAD 2 1 12 12 17
    EUR 10 16 15 15 19
    INR 12 3 5 19 7


    MultiIndex DF:



    >>> Dataframe B:

    Notional
    Bank Curency
    Bank_1 AUD 16
    CAD 13
    EUR 22
    Bank_2 AUD 24
    CAD 20
    EUR 17


    The goal is to:



    1) reindex B so that its currency level includes each currency in A's index. B would then look like this (see BRL and INR included, their Notional values are not important):



                        Notional
    Bank Curency
    Bank_1 AUD 16
    CAD 13
    EUR 22
    BRL 0
    INR 0
    Bank_2 AUD 24
    CAD 20
    EUR 17
    BRL 0
    INR 0


    2) reindex A so that it includes each Bank from the first level of B's index. A would then look like this:



                   AUD      BRL     CAD     EUR     INR
    Bank_1 AUD 7 19 11 11 4
    BRL 8 3 2 12 6
    CAD 2 1 12 12 17
    EUR 10 16 15 15 19
    INR 12 3 5 19 7
    Bank_2 AUD 7 19 11 11 4
    BRL 8 3 2 12 6
    CAD 2 1 12 12 17
    EUR 10 16 15 15 19
    INR 12 3 5 19 7


    The application of this will be on much larger dataframes so I need a pythonic way to do this.



    For context, ultimately I want to multiply A and B. I am trying to reindex to get matching indices as that was shown as a clean way to multiply dataframes of various index levels here:
    Pandas multiply dataframes with multiindex and overlapping index levels



    Thank you for any help.










    share|improve this question

























      2












      2








      2


      1






      is there a way to reindex two dataframes (of differing levels) so that they share a common index across all levels?



      Demo:



      Create a basic Dataframe named 'A':



      index = np.array(['AUD','BRL','CAD','EUR','INR'])
      data = np.random.randint(1, 20, (5,5))
      A = pd.DataFrame(data=data, index=index, columns=index)


      Create a MultiIndex Dataframe named 'B':



      np.random.seed(42)
      midx1 = pd.MultiIndex.from_product([['Bank_1', 'Bank_2'],
      ['AUD','CAD','EUR']], names=['Bank', 'Curency'])
      B = pd.DataFrame(np.random.randint(10,25,6), midx1)
      B.columns = ['Notional']


      Basic DF:



      >>> Dataframe A:

      AUD BRL CAD EUR INR
      AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7


      MultiIndex DF:



      >>> Dataframe B:

      Notional
      Bank Curency
      Bank_1 AUD 16
      CAD 13
      EUR 22
      Bank_2 AUD 24
      CAD 20
      EUR 17


      The goal is to:



      1) reindex B so that its currency level includes each currency in A's index. B would then look like this (see BRL and INR included, their Notional values are not important):



                          Notional
      Bank Curency
      Bank_1 AUD 16
      CAD 13
      EUR 22
      BRL 0
      INR 0
      Bank_2 AUD 24
      CAD 20
      EUR 17
      BRL 0
      INR 0


      2) reindex A so that it includes each Bank from the first level of B's index. A would then look like this:



                     AUD      BRL     CAD     EUR     INR
      Bank_1 AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7
      Bank_2 AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7


      The application of this will be on much larger dataframes so I need a pythonic way to do this.



      For context, ultimately I want to multiply A and B. I am trying to reindex to get matching indices as that was shown as a clean way to multiply dataframes of various index levels here:
      Pandas multiply dataframes with multiindex and overlapping index levels



      Thank you for any help.










      share|improve this question














      is there a way to reindex two dataframes (of differing levels) so that they share a common index across all levels?



      Demo:



      Create a basic Dataframe named 'A':



      index = np.array(['AUD','BRL','CAD','EUR','INR'])
      data = np.random.randint(1, 20, (5,5))
      A = pd.DataFrame(data=data, index=index, columns=index)


      Create a MultiIndex Dataframe named 'B':



      np.random.seed(42)
      midx1 = pd.MultiIndex.from_product([['Bank_1', 'Bank_2'],
      ['AUD','CAD','EUR']], names=['Bank', 'Curency'])
      B = pd.DataFrame(np.random.randint(10,25,6), midx1)
      B.columns = ['Notional']


      Basic DF:



      >>> Dataframe A:

      AUD BRL CAD EUR INR
      AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7


      MultiIndex DF:



      >>> Dataframe B:

      Notional
      Bank Curency
      Bank_1 AUD 16
      CAD 13
      EUR 22
      Bank_2 AUD 24
      CAD 20
      EUR 17


      The goal is to:



      1) reindex B so that its currency level includes each currency in A's index. B would then look like this (see BRL and INR included, their Notional values are not important):



                          Notional
      Bank Curency
      Bank_1 AUD 16
      CAD 13
      EUR 22
      BRL 0
      INR 0
      Bank_2 AUD 24
      CAD 20
      EUR 17
      BRL 0
      INR 0


      2) reindex A so that it includes each Bank from the first level of B's index. A would then look like this:



                     AUD      BRL     CAD     EUR     INR
      Bank_1 AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7
      Bank_2 AUD 7 19 11 11 4
      BRL 8 3 2 12 6
      CAD 2 1 12 12 17
      EUR 10 16 15 15 19
      INR 12 3 5 19 7


      The application of this will be on much larger dataframes so I need a pythonic way to do this.



      For context, ultimately I want to multiply A and B. I am trying to reindex to get matching indices as that was shown as a clean way to multiply dataframes of various index levels here:
      Pandas multiply dataframes with multiindex and overlapping index levels



      Thank you for any help.







      pandas dataframe multi-index






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 17:53









      BradBBradB

      133




      133
























          1 Answer
          1






          active

          oldest

          votes


















          2














          To get the B using reindex



          B.reindex( pd.MultiIndex.from_product([B.index.levels[0], 
          A.index], names=['Bank', 'Curency']),fill_value=0)

          Out[62]:
          Notional
          Bank Curency
          Bank_1 AUD 16
          BRL 0
          CAD 13
          EUR 22
          INR 0
          Bank_2 AUD 24
          BRL 0
          CAD 20
          EUR 17
          INR 0


          To get the A using concat



          pd.concat([A]*2,keys=B.index.levels[0])
          Out[69]:
          AUD BRL CAD EUR INR
          Bank
          Bank_1 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4
          Bank_2 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4





          share|improve this answer





















          • 2





            Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

            – Scott Boston
            Nov 13 '18 at 18:06











          • Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

            – BradB
            Nov 13 '18 at 21:46











          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%2f53286882%2fpandas-reindex-a-multiindex-dataframe%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














          To get the B using reindex



          B.reindex( pd.MultiIndex.from_product([B.index.levels[0], 
          A.index], names=['Bank', 'Curency']),fill_value=0)

          Out[62]:
          Notional
          Bank Curency
          Bank_1 AUD 16
          BRL 0
          CAD 13
          EUR 22
          INR 0
          Bank_2 AUD 24
          BRL 0
          CAD 20
          EUR 17
          INR 0


          To get the A using concat



          pd.concat([A]*2,keys=B.index.levels[0])
          Out[69]:
          AUD BRL CAD EUR INR
          Bank
          Bank_1 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4
          Bank_2 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4





          share|improve this answer





















          • 2





            Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

            – Scott Boston
            Nov 13 '18 at 18:06











          • Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

            – BradB
            Nov 13 '18 at 21:46
















          2














          To get the B using reindex



          B.reindex( pd.MultiIndex.from_product([B.index.levels[0], 
          A.index], names=['Bank', 'Curency']),fill_value=0)

          Out[62]:
          Notional
          Bank Curency
          Bank_1 AUD 16
          BRL 0
          CAD 13
          EUR 22
          INR 0
          Bank_2 AUD 24
          BRL 0
          CAD 20
          EUR 17
          INR 0


          To get the A using concat



          pd.concat([A]*2,keys=B.index.levels[0])
          Out[69]:
          AUD BRL CAD EUR INR
          Bank
          Bank_1 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4
          Bank_2 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4





          share|improve this answer





















          • 2





            Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

            – Scott Boston
            Nov 13 '18 at 18:06











          • Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

            – BradB
            Nov 13 '18 at 21:46














          2












          2








          2







          To get the B using reindex



          B.reindex( pd.MultiIndex.from_product([B.index.levels[0], 
          A.index], names=['Bank', 'Curency']),fill_value=0)

          Out[62]:
          Notional
          Bank Curency
          Bank_1 AUD 16
          BRL 0
          CAD 13
          EUR 22
          INR 0
          Bank_2 AUD 24
          BRL 0
          CAD 20
          EUR 17
          INR 0


          To get the A using concat



          pd.concat([A]*2,keys=B.index.levels[0])
          Out[69]:
          AUD BRL CAD EUR INR
          Bank
          Bank_1 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4
          Bank_2 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4





          share|improve this answer















          To get the B using reindex



          B.reindex( pd.MultiIndex.from_product([B.index.levels[0], 
          A.index], names=['Bank', 'Curency']),fill_value=0)

          Out[62]:
          Notional
          Bank Curency
          Bank_1 AUD 16
          BRL 0
          CAD 13
          EUR 22
          INR 0
          Bank_2 AUD 24
          BRL 0
          CAD 20
          EUR 17
          INR 0


          To get the A using concat



          pd.concat([A]*2,keys=B.index.levels[0])
          Out[69]:
          AUD BRL CAD EUR INR
          Bank
          Bank_1 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4
          Bank_2 AUD 10 5 10 14 1
          BRL 17 1 14 10 8
          CAD 3 7 3 15 2
          EUR 17 1 15 2 16
          INR 7 15 6 7 4






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 18:10

























          answered Nov 13 '18 at 18:00









          W-BW-B

          104k73165




          104k73165








          • 2





            Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

            – Scott Boston
            Nov 13 '18 at 18:06











          • Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

            – BradB
            Nov 13 '18 at 21:46














          • 2





            Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

            – Scott Boston
            Nov 13 '18 at 18:06











          • Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

            – BradB
            Nov 13 '18 at 21:46








          2




          2





          Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

          – Scott Boston
          Nov 13 '18 at 18:06





          Also, instead of hard coding ['Bank_1', 'Bank_2'], you can use get_level_values, like this B.index.get_level_values(0).unique().

          – Scott Boston
          Nov 13 '18 at 18:06













          Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

          – BradB
          Nov 13 '18 at 21:46





          Works - thank you both! As I mentioned above ultimately I want to multiply A and B. I thought that having created dataframes consisting of 5x5 matrices and 5x1 matrices for A and B respectively I would be able to multiply them, however, A.multiply(B) does not work. I'd like to multiply the notional amount in B by each currency row in A. e.g. 16*10, 0*5, 13*10, 22*14, 0*1 and so on. The final shape would be the same as that of A. If this is too convoluted of a question, let me know and I'll create a new entry.

          – BradB
          Nov 13 '18 at 21:46


















          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%2f53286882%2fpandas-reindex-a-multiindex-dataframe%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()