Pandas: Pad data-frame to max row length The Next CEO of Stack OverflowAdd one row to pandas DataFrameUse a list of values to select rows from a pandas dataframeHow to drop rows of Pandas DataFrame whose value in certain columns is NaN“Large data” work flows using pandasChange data type of columns in PandasHow do I get the row count of a Pandas dataframe?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valuePandas: Remove rows per group based on a condition

Can you teleport closer to a creature you are Frightened of?

What steps are necessary to read a Modern SSD in Medieval Europe?

What flight has the highest ratio of timezone difference to flight time?

Film where the government was corrupt with aliens, people sent to kill aliens are given rigged visors not showing the right aliens

Is Nisuin Biblical or Rabbinic?

Purpose of level-shifter with same in and out voltages

Is fine stranded wire ok for main supply line?

What does "shotgun unity" refer to here in this sentence?

What difference does it make using sed with/without whitespaces?

Spaces in which all closed sets are regular closed

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Getting Stale Gas Out of a Gas Tank w/out Dropping the Tank

Could a dragon use its wings to swim?

Airplane gently rocking its wings during whole flight

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

IC has pull-down resistors on SMBus lines?

How can the PCs determine if an item is a phylactery?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

What would be the main consequences for a country leaving the WTO?

How to get the last not-null value in an ordered column of a huge table?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Lucky Feat: How can "more than one creature spend a luck point to influence the outcome of a roll"?



Pandas: Pad data-frame to max row length



The Next CEO of Stack OverflowAdd one row to pandas DataFrameUse a list of values to select rows from a pandas dataframeHow to drop rows of Pandas DataFrame whose value in certain columns is NaN“Large data” work flows using pandasChange data type of columns in PandasHow do I get the row count of a Pandas dataframe?How to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasDeleting DataFrame row in Pandas based on column valuePandas: Remove rows per group based on a condition










0















I have data-frame like the following:



df = pd.DataFrame("id": [100, 200, 200, 300, 300, 300], "val1": [1.5, 2.5, 4.5, np.nan, 6.5, np.nan], "val2": [9.5, 7.5, 8.5, 3.5, np.nan, np.nan])


What I want to achieve is to zero pad each group (assuming that the data-frame is grouped by id), to the max number of rows for all groups. The max number of rows per id for the data-frame above is 3, so the resulting data-frame should look like the following:



df_true = pd.DataFrame("id": [100, 100, 100, 200, 200 ,200, 300, 300, 300], "val1": [1.5, 0, 0, 2.5, 4.5, 0, np.nan, 6.5, np.nan], "val2": [9.5, 0, 0, 7.5, 8.5, 0, 3.5, np.nan, np.nan])


Can someone point me in the right direction how to achieve that?










share|improve this question


























    0















    I have data-frame like the following:



    df = pd.DataFrame("id": [100, 200, 200, 300, 300, 300], "val1": [1.5, 2.5, 4.5, np.nan, 6.5, np.nan], "val2": [9.5, 7.5, 8.5, 3.5, np.nan, np.nan])


    What I want to achieve is to zero pad each group (assuming that the data-frame is grouped by id), to the max number of rows for all groups. The max number of rows per id for the data-frame above is 3, so the resulting data-frame should look like the following:



    df_true = pd.DataFrame("id": [100, 100, 100, 200, 200 ,200, 300, 300, 300], "val1": [1.5, 0, 0, 2.5, 4.5, 0, np.nan, 6.5, np.nan], "val2": [9.5, 0, 0, 7.5, 8.5, 0, 3.5, np.nan, np.nan])


    Can someone point me in the right direction how to achieve that?










    share|improve this question
























      0












      0








      0








      I have data-frame like the following:



      df = pd.DataFrame("id": [100, 200, 200, 300, 300, 300], "val1": [1.5, 2.5, 4.5, np.nan, 6.5, np.nan], "val2": [9.5, 7.5, 8.5, 3.5, np.nan, np.nan])


      What I want to achieve is to zero pad each group (assuming that the data-frame is grouped by id), to the max number of rows for all groups. The max number of rows per id for the data-frame above is 3, so the resulting data-frame should look like the following:



      df_true = pd.DataFrame("id": [100, 100, 100, 200, 200 ,200, 300, 300, 300], "val1": [1.5, 0, 0, 2.5, 4.5, 0, np.nan, 6.5, np.nan], "val2": [9.5, 0, 0, 7.5, 8.5, 0, 3.5, np.nan, np.nan])


      Can someone point me in the right direction how to achieve that?










      share|improve this question














      I have data-frame like the following:



      df = pd.DataFrame("id": [100, 200, 200, 300, 300, 300], "val1": [1.5, 2.5, 4.5, np.nan, 6.5, np.nan], "val2": [9.5, 7.5, 8.5, 3.5, np.nan, np.nan])


      What I want to achieve is to zero pad each group (assuming that the data-frame is grouped by id), to the max number of rows for all groups. The max number of rows per id for the data-frame above is 3, so the resulting data-frame should look like the following:



      df_true = pd.DataFrame("id": [100, 100, 100, 200, 200 ,200, 300, 300, 300], "val1": [1.5, 0, 0, 2.5, 4.5, 0, np.nan, 6.5, np.nan], "val2": [9.5, 0, 0, 7.5, 8.5, 0, 3.5, np.nan, np.nan])


      Can someone point me in the right direction how to achieve that?







      python pandas pandas-groupby






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 17:35









      gorjangorjan

      1,443615




      1,443615






















          1 Answer
          1






          active

          oldest

          votes


















          1














          So we do with cumcount with id then using stack and unstack



          df['new']=df.groupby('id').cumcount()
          df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
          df_true
          Out[908]:
          id val1 val2
          new
          0 100 1.5 9.5
          1 100 0.0 0.0
          2 100 0.0 0.0
          0 200 2.5 7.5
          1 200 4.5 8.5
          2 200 0.0 0.0
          0 300 NaN 3.5
          1 300 6.5 NaN
          2 300 NaN NaN





          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%2f55068265%2fpandas-pad-data-frame-to-max-row-length%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














            So we do with cumcount with id then using stack and unstack



            df['new']=df.groupby('id').cumcount()
            df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
            df_true
            Out[908]:
            id val1 val2
            new
            0 100 1.5 9.5
            1 100 0.0 0.0
            2 100 0.0 0.0
            0 200 2.5 7.5
            1 200 4.5 8.5
            2 200 0.0 0.0
            0 300 NaN 3.5
            1 300 6.5 NaN
            2 300 NaN NaN





            share|improve this answer



























              1














              So we do with cumcount with id then using stack and unstack



              df['new']=df.groupby('id').cumcount()
              df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
              df_true
              Out[908]:
              id val1 val2
              new
              0 100 1.5 9.5
              1 100 0.0 0.0
              2 100 0.0 0.0
              0 200 2.5 7.5
              1 200 4.5 8.5
              2 200 0.0 0.0
              0 300 NaN 3.5
              1 300 6.5 NaN
              2 300 NaN NaN





              share|improve this answer

























                1












                1








                1







                So we do with cumcount with id then using stack and unstack



                df['new']=df.groupby('id').cumcount()
                df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
                df_true
                Out[908]:
                id val1 val2
                new
                0 100 1.5 9.5
                1 100 0.0 0.0
                2 100 0.0 0.0
                0 200 2.5 7.5
                1 200 4.5 8.5
                2 200 0.0 0.0
                0 300 NaN 3.5
                1 300 6.5 NaN
                2 300 NaN NaN





                share|improve this answer













                So we do with cumcount with id then using stack and unstack



                df['new']=df.groupby('id').cumcount()
                df_true=df.set_index(['id','new']).unstack(fill_value=0).stack(dropna=False).reset_index('id')
                df_true
                Out[908]:
                id val1 val2
                new
                0 100 1.5 9.5
                1 100 0.0 0.0
                2 100 0.0 0.0
                0 200 2.5 7.5
                1 200 4.5 8.5
                2 200 0.0 0.0
                0 300 NaN 3.5
                1 300 6.5 NaN
                2 300 NaN NaN






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 17:39









                Wen-BenWen-Ben

                122k83571




                122k83571





























                    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%2f55068265%2fpandas-pad-data-frame-to-max-row-length%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

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page