Merging mulitple rows to one row of a dataframe columnHow to merge two dictionaries in a single expression?How to sort a dataframe by multiple column(s)Selecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrameCreating an empty Pandas DataFrame, then filling it?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers

The pirate treasure of Leatherback Atoll

How do you say "to hell with everything" in French?

RANK used in 'where' returns invalid column, but exists in results set

Stack class in Java 8

Is there a "right" way to interpret a novel, if not, how do we make sure our novel is interpreted correctly?

What makes things real?

How is lower/no gravity simulated on a planet with gravity, without leaving the surface?

Is mountain bike good for long distances?

After a few interviews, What should I do after told to wait?

Is every sentence we write or utter either true or false?

If every star in the universe except the Sun were destroyed, would we die?

Do you need to burn fuel between gravity assists?

How do I decide when to use MAPE, SMAPE and MASE for time series analysis on stock forecasting

Sloth and the Hindrances

How invisible hand adjusts stock prices if company is listed on multiple exchanges, under multiple currencies, and one of the currencies plunges?

Chandrayaan 2: Why is Vikram Lander's life limited to 14 Days?

What is the difference between tl_to_str:V and tl_to_str:N?

Can you mark a new target with the Hunter's Mark spell if the original target shifts to a different plane?

How do Scrum teams manage their dependencies on other teams?

pgfgantt: month displayed as single letter

How can Schrödinger's cat be both dead and alive?

How would two worlds first establish an exchange rate between their currencies

Gap in tcolorbox after title

Maze generator & animator in Python



Merging mulitple rows to one row of a dataframe column


How to merge two dictionaries in a single expression?How to sort a dataframe by multiple column(s)Selecting multiple columns in a pandas dataframeRenaming columns in pandasAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrameCreating an empty Pandas DataFrame, then filling it?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















My Current dataframe was like below,



 0 1 2
0 HA-567034786 AB-1018724 None
1 AB-6348403 HA-7298656 None


After using the apply(), I just make it like,



def make_dict(row):
s = set(x for x in row if x)
return x: list(s - x) for x in s

result = df.apply(make_dict, axis=1).to_frame(name = 'duplicates')

duplicates
1 'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786']
2 'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']


Now I'm stucked on to make it a single dimentional dictionary like below,




'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786'],
'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']










share|improve this question






























    1















    My Current dataframe was like below,



     0 1 2
    0 HA-567034786 AB-1018724 None
    1 AB-6348403 HA-7298656 None


    After using the apply(), I just make it like,



    def make_dict(row):
    s = set(x for x in row if x)
    return x: list(s - x) for x in s

    result = df.apply(make_dict, axis=1).to_frame(name = 'duplicates')

    duplicates
    1 'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786']
    2 'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']


    Now I'm stucked on to make it a single dimentional dictionary like below,




    'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786'],
    'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']










    share|improve this question


























      1












      1








      1








      My Current dataframe was like below,



       0 1 2
      0 HA-567034786 AB-1018724 None
      1 AB-6348403 HA-7298656 None


      After using the apply(), I just make it like,



      def make_dict(row):
      s = set(x for x in row if x)
      return x: list(s - x) for x in s

      result = df.apply(make_dict, axis=1).to_frame(name = 'duplicates')

      duplicates
      1 'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786']
      2 'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']


      Now I'm stucked on to make it a single dimentional dictionary like below,




      'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786'],
      'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']










      share|improve this question














      My Current dataframe was like below,



       0 1 2
      0 HA-567034786 AB-1018724 None
      1 AB-6348403 HA-7298656 None


      After using the apply(), I just make it like,



      def make_dict(row):
      s = set(x for x in row if x)
      return x: list(s - x) for x in s

      result = df.apply(make_dict, axis=1).to_frame(name = 'duplicates')

      duplicates
      1 'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786']
      2 'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']


      Now I'm stucked on to make it a single dimentional dictionary like below,




      'HA-567034786': ['AB-1018724'],'AB-1018724':['HA-567034786'],
      'AB-6348403': ['HA-7298656'],'HA-7298656':['AB-6348403']







      python pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 28 at 7:32









      Always SunnyAlways Sunny

      18.9k3 gold badges32 silver badges56 bronze badges




      18.9k3 gold badges32 silver badges56 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          1
















          Instead apply use dictionary comprehension with flattening:



          print (df)
          0 1
          0 HA-567034786 AB-1018724
          1 AB-6348403 HA-7298656

          def make_dict(row):
          s = set(x for x in row if x)
          return x: list(s - x) for x in s

          result = k:v for x in df.values for k, v in make_dict(x).items()

          print (result)
          'HA-567034786': ['AB-1018724'],
          'AB-1018724': ['HA-567034786'],
          'HA-7298656': ['AB-6348403'],
          'AB-6348403': ['HA-7298656']


          Another solution with apply:



          result = k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()





          share|improve this answer






















          • 1





            You're a star mate :)

            – Always Sunny
            Mar 28 at 9:03











          • daily I learn a lot from your answers :)

            – Always Sunny
            Mar 28 at 9:10


















          1
















          Also you can use collections.ChainMap() to group all the dictionaries to one as:



          from collections import ChainMap
          res =dict(ChainMap(*result['duplicates']))





          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/4.0/"u003ecc by-sa 4.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%2f55392261%2fmerging-mulitple-rows-to-one-row-of-a-dataframe-column%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









            1
















            Instead apply use dictionary comprehension with flattening:



            print (df)
            0 1
            0 HA-567034786 AB-1018724
            1 AB-6348403 HA-7298656

            def make_dict(row):
            s = set(x for x in row if x)
            return x: list(s - x) for x in s

            result = k:v for x in df.values for k, v in make_dict(x).items()

            print (result)
            'HA-567034786': ['AB-1018724'],
            'AB-1018724': ['HA-567034786'],
            'HA-7298656': ['AB-6348403'],
            'AB-6348403': ['HA-7298656']


            Another solution with apply:



            result = k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()





            share|improve this answer






















            • 1





              You're a star mate :)

              – Always Sunny
              Mar 28 at 9:03











            • daily I learn a lot from your answers :)

              – Always Sunny
              Mar 28 at 9:10















            1
















            Instead apply use dictionary comprehension with flattening:



            print (df)
            0 1
            0 HA-567034786 AB-1018724
            1 AB-6348403 HA-7298656

            def make_dict(row):
            s = set(x for x in row if x)
            return x: list(s - x) for x in s

            result = k:v for x in df.values for k, v in make_dict(x).items()

            print (result)
            'HA-567034786': ['AB-1018724'],
            'AB-1018724': ['HA-567034786'],
            'HA-7298656': ['AB-6348403'],
            'AB-6348403': ['HA-7298656']


            Another solution with apply:



            result = k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()





            share|improve this answer






















            • 1





              You're a star mate :)

              – Always Sunny
              Mar 28 at 9:03











            • daily I learn a lot from your answers :)

              – Always Sunny
              Mar 28 at 9:10













            1














            1










            1









            Instead apply use dictionary comprehension with flattening:



            print (df)
            0 1
            0 HA-567034786 AB-1018724
            1 AB-6348403 HA-7298656

            def make_dict(row):
            s = set(x for x in row if x)
            return x: list(s - x) for x in s

            result = k:v for x in df.values for k, v in make_dict(x).items()

            print (result)
            'HA-567034786': ['AB-1018724'],
            'AB-1018724': ['HA-567034786'],
            'HA-7298656': ['AB-6348403'],
            'AB-6348403': ['HA-7298656']


            Another solution with apply:



            result = k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()





            share|improve this answer















            Instead apply use dictionary comprehension with flattening:



            print (df)
            0 1
            0 HA-567034786 AB-1018724
            1 AB-6348403 HA-7298656

            def make_dict(row):
            s = set(x for x in row if x)
            return x: list(s - x) for x in s

            result = k:v for x in df.values for k, v in make_dict(x).items()

            print (result)
            'HA-567034786': ['AB-1018724'],
            'AB-1018724': ['HA-567034786'],
            'HA-7298656': ['AB-6348403'],
            'AB-6348403': ['HA-7298656']


            Another solution with apply:



            result = k:v for x in df.apply(make_dict, axis=1) for k, v in x.items()






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 28 at 7:46

























            answered Mar 28 at 7:38









            jezraeljezrael

            407k32 gold badges425 silver badges491 bronze badges




            407k32 gold badges425 silver badges491 bronze badges










            • 1





              You're a star mate :)

              – Always Sunny
              Mar 28 at 9:03











            • daily I learn a lot from your answers :)

              – Always Sunny
              Mar 28 at 9:10












            • 1





              You're a star mate :)

              – Always Sunny
              Mar 28 at 9:03











            • daily I learn a lot from your answers :)

              – Always Sunny
              Mar 28 at 9:10







            1




            1





            You're a star mate :)

            – Always Sunny
            Mar 28 at 9:03





            You're a star mate :)

            – Always Sunny
            Mar 28 at 9:03













            daily I learn a lot from your answers :)

            – Always Sunny
            Mar 28 at 9:10





            daily I learn a lot from your answers :)

            – Always Sunny
            Mar 28 at 9:10













            1
















            Also you can use collections.ChainMap() to group all the dictionaries to one as:



            from collections import ChainMap
            res =dict(ChainMap(*result['duplicates']))





            share|improve this answer





























              1
















              Also you can use collections.ChainMap() to group all the dictionaries to one as:



              from collections import ChainMap
              res =dict(ChainMap(*result['duplicates']))





              share|improve this answer



























                1














                1










                1









                Also you can use collections.ChainMap() to group all the dictionaries to one as:



                from collections import ChainMap
                res =dict(ChainMap(*result['duplicates']))





                share|improve this answer













                Also you can use collections.ChainMap() to group all the dictionaries to one as:



                from collections import ChainMap
                res =dict(ChainMap(*result['duplicates']))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 9:06









                LoochieLoochie

                1,0363 silver badges11 bronze badges




                1,0363 silver badges11 bronze badges































                    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%2f55392261%2fmerging-mulitple-rows-to-one-row-of-a-dataframe-column%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현