Pandas: create new (sub-level) columns in a multi-index dataframe and assign valuesSelecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaN“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valueGet list from pandas DataFrame column headersHow to convert index of a pandas dataframe into a column?pandas 0.20.3 DataFrame behavior changes for pyspark.ml.vectors object in a column

How could a planet have erratic days?

What does chmod -u do?

What if a revenant (monster) gains fire resistance?

When were female captains banned from Starfleet?

15% tax on $7.5k earnings. Is that right?

Hero deduces identity of a killer

Multiplicative persistence

What is Cash Advance APR?

Why did the EU agree to delay the Brexit deadline?

Why is the "ls" command showing permissions of files in a FAT32 partition?

How to fade a semiplane defined by line?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

How can "mimic phobia" be cured or prevented?

How to hide some fields of struct in C?

What are the advantages of simplicial model categories over non-simplicial ones?

Can a Canadian Travel to the USA twice, less than 180 days each time?

What happens if you are holding an Iron Flask with a demon inside and walk into an Antimagic Field?

Pre-mixing cryogenic fuels and using only one fuel tank

Why should universal income be universal?

The IT department bottlenecks progress. How should I handle this?

Biological Blimps: Propulsion

Why would a new[] expression ever invoke a destructor?

Can I still be respawned if I die by falling off the map?

Fear of getting stuck on one programming language / technology that is not used in my country



Pandas: create new (sub-level) columns in a multi-index dataframe and assign values


Selecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaN“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valueGet list from pandas DataFrame column headersHow to convert index of a pandas dataframe into a column?pandas 0.20.3 DataFrame behavior changes for pyspark.ml.vectors object in a column













1















Let's be given a data-frame like the following one:



import pandas as pd 
import numpy as np

a = ['a', 'b']
b = ['i', 'ii']
mi = pd.MultiIndex.from_product([a,b], names=['first', 'second'])
A = pd.DataFrame(np.zeros([3,4]), columns=mi)


first a b
second i ii i ii
0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0


I would like to create new columns iii for all first-level columns and assign the value of a new array (of matching size). I tried the following, to no avail.



A.loc[:,pd.IndexSlice[:,'iii']] = np.arange(6).reshape(3,-1)


The result should look like this:



 a b
i ii iii i ii iii
0 0.0 0.0 0.0 0.0 0.0 1.0
1 0.0 0.0 2.0 0.0 0.0 3.0
2 0.0 0.0 4.0 0.0 0.0 5.0









share|improve this question


























    1















    Let's be given a data-frame like the following one:



    import pandas as pd 
    import numpy as np

    a = ['a', 'b']
    b = ['i', 'ii']
    mi = pd.MultiIndex.from_product([a,b], names=['first', 'second'])
    A = pd.DataFrame(np.zeros([3,4]), columns=mi)


    first a b
    second i ii i ii
    0 0.0 0.0 0.0 0.0
    1 0.0 0.0 0.0 0.0
    2 0.0 0.0 0.0 0.0


    I would like to create new columns iii for all first-level columns and assign the value of a new array (of matching size). I tried the following, to no avail.



    A.loc[:,pd.IndexSlice[:,'iii']] = np.arange(6).reshape(3,-1)


    The result should look like this:



     a b
    i ii iii i ii iii
    0 0.0 0.0 0.0 0.0 0.0 1.0
    1 0.0 0.0 2.0 0.0 0.0 3.0
    2 0.0 0.0 4.0 0.0 0.0 5.0









    share|improve this question
























      1












      1








      1








      Let's be given a data-frame like the following one:



      import pandas as pd 
      import numpy as np

      a = ['a', 'b']
      b = ['i', 'ii']
      mi = pd.MultiIndex.from_product([a,b], names=['first', 'second'])
      A = pd.DataFrame(np.zeros([3,4]), columns=mi)


      first a b
      second i ii i ii
      0 0.0 0.0 0.0 0.0
      1 0.0 0.0 0.0 0.0
      2 0.0 0.0 0.0 0.0


      I would like to create new columns iii for all first-level columns and assign the value of a new array (of matching size). I tried the following, to no avail.



      A.loc[:,pd.IndexSlice[:,'iii']] = np.arange(6).reshape(3,-1)


      The result should look like this:



       a b
      i ii iii i ii iii
      0 0.0 0.0 0.0 0.0 0.0 1.0
      1 0.0 0.0 2.0 0.0 0.0 3.0
      2 0.0 0.0 4.0 0.0 0.0 5.0









      share|improve this question














      Let's be given a data-frame like the following one:



      import pandas as pd 
      import numpy as np

      a = ['a', 'b']
      b = ['i', 'ii']
      mi = pd.MultiIndex.from_product([a,b], names=['first', 'second'])
      A = pd.DataFrame(np.zeros([3,4]), columns=mi)


      first a b
      second i ii i ii
      0 0.0 0.0 0.0 0.0
      1 0.0 0.0 0.0 0.0
      2 0.0 0.0 0.0 0.0


      I would like to create new columns iii for all first-level columns and assign the value of a new array (of matching size). I tried the following, to no avail.



      A.loc[:,pd.IndexSlice[:,'iii']] = np.arange(6).reshape(3,-1)


      The result should look like this:



       a b
      i ii iii i ii iii
      0 0.0 0.0 0.0 0.0 0.0 1.0
      1 0.0 0.0 2.0 0.0 0.0 3.0
      2 0.0 0.0 4.0 0.0 0.0 5.0






      python pandas multi-index






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 2:31









      normaniusnormanius

      1,6491332




      1,6491332






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Since you have multiple index in columns , I recommend create the additional append df , then concat it back



          appenddf=pd.DataFrame(np.arange(6).reshape(3,-1), 
          index=A.index,
          columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

          appenddf
          a b
          iii iii
          0 0 1
          1 2 3
          2 4 5
          A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
          A
          first a b
          second i ii iii i ii iii
          0 0.0 0.0 0 0.0 0.0 1
          1 0.0 0.0 2 0.0 0.0 3
          2 0.0 0.0 4 0.0 0.0 5



          Another workable solution



          for i,x in enumerate(A.columns.levels[0]):
          A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
          A
          first a b a b
          second i ii i ii iii iii
          0 0.0 0.0 0.0 0.0 0 1
          1 0.0 0.0 0.0 0.0 2 3
          2 0.0 0.0 0.0 0.0 4 5
          # here I did not add `sort_index`





          share|improve this answer






















            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%2f55055885%2fpandas-create-new-sub-level-columns-in-a-multi-index-dataframe-and-assign-val%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









            1














            Since you have multiple index in columns , I recommend create the additional append df , then concat it back



            appenddf=pd.DataFrame(np.arange(6).reshape(3,-1), 
            index=A.index,
            columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

            appenddf
            a b
            iii iii
            0 0 1
            1 2 3
            2 4 5
            A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
            A
            first a b
            second i ii iii i ii iii
            0 0.0 0.0 0 0.0 0.0 1
            1 0.0 0.0 2 0.0 0.0 3
            2 0.0 0.0 4 0.0 0.0 5



            Another workable solution



            for i,x in enumerate(A.columns.levels[0]):
            A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
            A
            first a b a b
            second i ii i ii iii iii
            0 0.0 0.0 0.0 0.0 0 1
            1 0.0 0.0 0.0 0.0 2 3
            2 0.0 0.0 0.0 0.0 4 5
            # here I did not add `sort_index`





            share|improve this answer



























              1














              Since you have multiple index in columns , I recommend create the additional append df , then concat it back



              appenddf=pd.DataFrame(np.arange(6).reshape(3,-1), 
              index=A.index,
              columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

              appenddf
              a b
              iii iii
              0 0 1
              1 2 3
              2 4 5
              A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
              A
              first a b
              second i ii iii i ii iii
              0 0.0 0.0 0 0.0 0.0 1
              1 0.0 0.0 2 0.0 0.0 3
              2 0.0 0.0 4 0.0 0.0 5



              Another workable solution



              for i,x in enumerate(A.columns.levels[0]):
              A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
              A
              first a b a b
              second i ii i ii iii iii
              0 0.0 0.0 0.0 0.0 0 1
              1 0.0 0.0 0.0 0.0 2 3
              2 0.0 0.0 0.0 0.0 4 5
              # here I did not add `sort_index`





              share|improve this answer

























                1












                1








                1







                Since you have multiple index in columns , I recommend create the additional append df , then concat it back



                appenddf=pd.DataFrame(np.arange(6).reshape(3,-1), 
                index=A.index,
                columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

                appenddf
                a b
                iii iii
                0 0 1
                1 2 3
                2 4 5
                A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
                A
                first a b
                second i ii iii i ii iii
                0 0.0 0.0 0 0.0 0.0 1
                1 0.0 0.0 2 0.0 0.0 3
                2 0.0 0.0 4 0.0 0.0 5



                Another workable solution



                for i,x in enumerate(A.columns.levels[0]):
                A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
                A
                first a b a b
                second i ii i ii iii iii
                0 0.0 0.0 0.0 0.0 0 1
                1 0.0 0.0 0.0 0.0 2 3
                2 0.0 0.0 0.0 0.0 4 5
                # here I did not add `sort_index`





                share|improve this answer













                Since you have multiple index in columns , I recommend create the additional append df , then concat it back



                appenddf=pd.DataFrame(np.arange(6).reshape(3,-1), 
                index=A.index,
                columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

                appenddf
                a b
                iii iii
                0 0 1
                1 2 3
                2 4 5
                A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
                A
                first a b
                second i ii iii i ii iii
                0 0.0 0.0 0 0.0 0.0 1
                1 0.0 0.0 2 0.0 0.0 3
                2 0.0 0.0 4 0.0 0.0 5



                Another workable solution



                for i,x in enumerate(A.columns.levels[0]):
                A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
                A
                first a b a b
                second i ii i ii iii iii
                0 0.0 0.0 0.0 0.0 0 1
                1 0.0 0.0 0.0 0.0 2 3
                2 0.0 0.0 0.0 0.0 4 5
                # here I did not add `sort_index`






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 2:39









                Wen-BenWen-Ben

                119k83569




                119k83569





























                    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%2f55055885%2fpandas-create-new-sub-level-columns-in-a-multi-index-dataframe-and-assign-val%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

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme