Python: How to place columns with identical names from different dataframes adjacent to each other? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to sort a dataframe by multiple column(s)Adding new column to existing DataFrame in Python pandasHow to change the order of DataFrame columns?Delete column from pandas DataFrame by column name“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headersCreating a pandas DataFrame from columns of other DataFrames with similar indexesCopying data from one pandas dataframe to other based on column valuePandas how to add the counters for matching rows between two dataframe columns

Should I use a zero-interest credit card for a large one-time purchase?

Where are Serre’s lectures at Collège de France to be found?

For a new assistant professor in CS, how to build/manage a publication pipeline

Dating a Former Employee

Can an alien society believe that their star system is the universe?

How could we fake a moon landing now?

Is it fair for a professor to grade us on the possession of past papers?

Maximum summed powersets with non-adjacent items

Why aren't air breathing engines used as small first stages?

How come Sam didn't become Lord of Horn Hill?

Around usage results

When the Haste spell ends on a creature, do attackers have advantage against that creature?

Amount of permutations on an NxNxN Rubik's Cube

Is there a kind of relay only consumes power when switching?

How does the math work when buying airline miles?

Is it cost-effective to upgrade an old-ish Giant Escape R3 commuter bike with entry-level branded parts (wheels, drivetrain)?

また usage in a dictionary

Delete nth line from bottom

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

Fantasy story; one type of magic grows in power with use, but the more powerful they are, they more they are drawn to travel to their source

An adverb for when you're not exaggerating

What does "lightly crushed" mean for cardamon pods?

What is homebrew?

Did MS DOS itself ever use blinking text?



Python: How to place columns with identical names from different dataframes adjacent to each other?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to sort a dataframe by multiple column(s)Adding new column to existing DataFrame in Python pandasHow to change the order of DataFrame columns?Delete column from pandas DataFrame by column name“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headersCreating a pandas DataFrame from columns of other DataFrames with similar indexesCopying data from one pandas dataframe to other based on column valuePandas how to add the counters for matching rows between two dataframe columns



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I would like to know if there's a way in Python to place columns from different dataframes with the same names (or related names) adjacent to each other.



I know there's the option to use JOIN, but I would like to make a function from the scratch that can achieve the same.



Example:



Let's assume 2 dataframes df1 and df2



df1 is



id A B
50 1 5
60 2 6
70 3 7
80 4 8


df2 is



id A_1 B_1
50 a b
60 c d
70 e f
80 g h


Expected Output: A new dataframe, say df3, looking like this



 id A A_1 B B_1
50 1 a 5 b
60 2 c 6 d
70 3 e 7 f
80 4 g 8 h









share|improve this question






























    2















    I would like to know if there's a way in Python to place columns from different dataframes with the same names (or related names) adjacent to each other.



    I know there's the option to use JOIN, but I would like to make a function from the scratch that can achieve the same.



    Example:



    Let's assume 2 dataframes df1 and df2



    df1 is



    id A B
    50 1 5
    60 2 6
    70 3 7
    80 4 8


    df2 is



    id A_1 B_1
    50 a b
    60 c d
    70 e f
    80 g h


    Expected Output: A new dataframe, say df3, looking like this



     id A A_1 B B_1
    50 1 a 5 b
    60 2 c 6 d
    70 3 e 7 f
    80 4 g 8 h









    share|improve this question


























      2












      2








      2








      I would like to know if there's a way in Python to place columns from different dataframes with the same names (or related names) adjacent to each other.



      I know there's the option to use JOIN, but I would like to make a function from the scratch that can achieve the same.



      Example:



      Let's assume 2 dataframes df1 and df2



      df1 is



      id A B
      50 1 5
      60 2 6
      70 3 7
      80 4 8


      df2 is



      id A_1 B_1
      50 a b
      60 c d
      70 e f
      80 g h


      Expected Output: A new dataframe, say df3, looking like this



       id A A_1 B B_1
      50 1 a 5 b
      60 2 c 6 d
      70 3 e 7 f
      80 4 g 8 h









      share|improve this question
















      I would like to know if there's a way in Python to place columns from different dataframes with the same names (or related names) adjacent to each other.



      I know there's the option to use JOIN, but I would like to make a function from the scratch that can achieve the same.



      Example:



      Let's assume 2 dataframes df1 and df2



      df1 is



      id A B
      50 1 5
      60 2 6
      70 3 7
      80 4 8


      df2 is



      id A_1 B_1
      50 a b
      60 c d
      70 e f
      80 g h


      Expected Output: A new dataframe, say df3, looking like this



       id A A_1 B B_1
      50 1 a 5 b
      60 2 c 6 d
      70 3 e 7 f
      80 4 g 8 h






      python python-3.x pandas dataframe






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 19:02







      Bibliophile20

















      asked Mar 8 at 18:51









      Bibliophile20Bibliophile20

      18910




      18910






















          2 Answers
          2






          active

          oldest

          votes


















          2














          you can use sorted() with column names like:



          m=pd.concat([df1.set_index('id'),df2.set_index('id')],axis=1)
          m[(sorted(m.columns))].reset_index()

          id A A_1 B B_1
          0 50 1 a 5 b
          1 60 2 c 6 d
          2 70 3 e 7 f
          3 80 4 g 8 h





          share|improve this answer






























            1














            First you join the 2 dataframes -



            df3 = df1.join(df2, how='inner')


            And then you can sort the index -



            df3 = df3.sort_index(axis=1)





            share|improve this answer























            • Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

              – Bibliophile20
              Mar 8 at 19:02











            • From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

              – Mortz
              Mar 8 at 19:15











            • Yes, I was thinking about the same. Thanks

              – Bibliophile20
              Mar 8 at 20:01











            • Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

              – Bibliophile20
              Mar 9 at 13:45











            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%2f55069309%2fpython-how-to-place-columns-with-identical-names-from-different-dataframes-adja%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            you can use sorted() with column names like:



            m=pd.concat([df1.set_index('id'),df2.set_index('id')],axis=1)
            m[(sorted(m.columns))].reset_index()

            id A A_1 B B_1
            0 50 1 a 5 b
            1 60 2 c 6 d
            2 70 3 e 7 f
            3 80 4 g 8 h





            share|improve this answer



























              2














              you can use sorted() with column names like:



              m=pd.concat([df1.set_index('id'),df2.set_index('id')],axis=1)
              m[(sorted(m.columns))].reset_index()

              id A A_1 B B_1
              0 50 1 a 5 b
              1 60 2 c 6 d
              2 70 3 e 7 f
              3 80 4 g 8 h





              share|improve this answer

























                2












                2








                2







                you can use sorted() with column names like:



                m=pd.concat([df1.set_index('id'),df2.set_index('id')],axis=1)
                m[(sorted(m.columns))].reset_index()

                id A A_1 B B_1
                0 50 1 a 5 b
                1 60 2 c 6 d
                2 70 3 e 7 f
                3 80 4 g 8 h





                share|improve this answer













                you can use sorted() with column names like:



                m=pd.concat([df1.set_index('id'),df2.set_index('id')],axis=1)
                m[(sorted(m.columns))].reset_index()

                id A A_1 B B_1
                0 50 1 a 5 b
                1 60 2 c 6 d
                2 70 3 e 7 f
                3 80 4 g 8 h






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 19:11









                anky_91anky_91

                10.8k2922




                10.8k2922























                    1














                    First you join the 2 dataframes -



                    df3 = df1.join(df2, how='inner')


                    And then you can sort the index -



                    df3 = df3.sort_index(axis=1)





                    share|improve this answer























                    • Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                      – Bibliophile20
                      Mar 8 at 19:02











                    • From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                      – Mortz
                      Mar 8 at 19:15











                    • Yes, I was thinking about the same. Thanks

                      – Bibliophile20
                      Mar 8 at 20:01











                    • Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                      – Bibliophile20
                      Mar 9 at 13:45















                    1














                    First you join the 2 dataframes -



                    df3 = df1.join(df2, how='inner')


                    And then you can sort the index -



                    df3 = df3.sort_index(axis=1)





                    share|improve this answer























                    • Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                      – Bibliophile20
                      Mar 8 at 19:02











                    • From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                      – Mortz
                      Mar 8 at 19:15











                    • Yes, I was thinking about the same. Thanks

                      – Bibliophile20
                      Mar 8 at 20:01











                    • Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                      – Bibliophile20
                      Mar 9 at 13:45













                    1












                    1








                    1







                    First you join the 2 dataframes -



                    df3 = df1.join(df2, how='inner')


                    And then you can sort the index -



                    df3 = df3.sort_index(axis=1)





                    share|improve this answer













                    First you join the 2 dataframes -



                    df3 = df1.join(df2, how='inner')


                    And then you can sort the index -



                    df3 = df3.sort_index(axis=1)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 8 at 18:59









                    MortzMortz

                    857619




                    857619












                    • Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                      – Bibliophile20
                      Mar 8 at 19:02











                    • From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                      – Mortz
                      Mar 8 at 19:15











                    • Yes, I was thinking about the same. Thanks

                      – Bibliophile20
                      Mar 8 at 20:01











                    • Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                      – Bibliophile20
                      Mar 9 at 13:45

















                    • Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                      – Bibliophile20
                      Mar 8 at 19:02











                    • From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                      – Mortz
                      Mar 8 at 19:15











                    • Yes, I was thinking about the same. Thanks

                      – Bibliophile20
                      Mar 8 at 20:01











                    • Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                      – Bibliophile20
                      Mar 9 at 13:45
















                    Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                    – Bibliophile20
                    Mar 8 at 19:02





                    Hey, @Mortz. Thank you for your response. I am aware that a join could be used, but I was wondering if a function can be made from scratch to achieve the same. Thanks

                    – Bibliophile20
                    Mar 8 at 19:02













                    From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                    – Mortz
                    Mar 8 at 19:15





                    From scratch? Can you clarify? Do you mean not using the pandas library at all? Maybe, you can take a look at the pandas codebase to get an idea on how such functionality is implemented

                    – Mortz
                    Mar 8 at 19:15













                    Yes, I was thinking about the same. Thanks

                    – Bibliophile20
                    Mar 8 at 20:01





                    Yes, I was thinking about the same. Thanks

                    – Bibliophile20
                    Mar 8 at 20:01













                    Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                    – Bibliophile20
                    Mar 9 at 13:45





                    Hey @Mortz, when I try your method, I am getting the following error TypeError: '<' not supported between instances of 'str' and 'int'

                    – Bibliophile20
                    Mar 9 at 13:45

















                    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%2f55069309%2fpython-how-to-place-columns-with-identical-names-from-different-dataframes-adja%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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved