groupby and function call in pandas











up vote
4
down vote

favorite












I have a dataframe where i have a column "Name". Name have multiples values like sample1, sample2, sample3. I want to apply a function to all those groups where value in Name column is same.



Output:



   Name  Value  Result
0 Name1 2 5
1 Name1 3 5
2 Name2 1 11
3 Name2 4 11
4 Name2 6 11
5 Name3 8 10
6 Name3 2 10









share|improve this question
























  • Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
    – DatHydroGuy
    2 days ago















up vote
4
down vote

favorite












I have a dataframe where i have a column "Name". Name have multiples values like sample1, sample2, sample3. I want to apply a function to all those groups where value in Name column is same.



Output:



   Name  Value  Result
0 Name1 2 5
1 Name1 3 5
2 Name2 1 11
3 Name2 4 11
4 Name2 6 11
5 Name3 8 10
6 Name3 2 10









share|improve this question
























  • Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
    – DatHydroGuy
    2 days ago













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I have a dataframe where i have a column "Name". Name have multiples values like sample1, sample2, sample3. I want to apply a function to all those groups where value in Name column is same.



Output:



   Name  Value  Result
0 Name1 2 5
1 Name1 3 5
2 Name2 1 11
3 Name2 4 11
4 Name2 6 11
5 Name3 8 10
6 Name3 2 10









share|improve this question















I have a dataframe where i have a column "Name". Name have multiples values like sample1, sample2, sample3. I want to apply a function to all those groups where value in Name column is same.



Output:



   Name  Value  Result
0 Name1 2 5
1 Name1 3 5
2 Name2 1 11
3 Name2 4 11
4 Name2 6 11
5 Name3 8 10
6 Name3 2 10






python python-3.x pandas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









nixon

83116




83116










asked 2 days ago









Chetan P

477




477












  • Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
    – DatHydroGuy
    2 days ago


















  • Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
    – DatHydroGuy
    2 days ago
















Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
– DatHydroGuy
2 days ago




Have you looked at the Pandas groupby function? pandas.pydata.org/pandas-docs/stable/groupby.html
– DatHydroGuy
2 days ago












3 Answers
3






active

oldest

votes

















up vote
2
down vote



accepted










Looks like you want a groupby.apply. Something like this should work:



import pandas as pd

df = # ... load your data

def group_sum(g):
g["Result"] = g["Value"].sum()
return g

df_grouped = df.groupby("Name").apply(group_sum)


Edit: Alexandre Nixon's answer is better for this use case.






share|improve this answer










New contributor




johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    up vote
    0
    down vote













    You want to use transform for that, which returns a dataframe with the transformed values and the same dimension.



    a['Result'] = a.groupby('Name').transform(lambda x: x.sum())


    For example if you have:



    df = pd.DataFrame({'Name':['Name2','Name2', 'Name3'], 
    'Value':[1,2,4]},
    columns = ['Name','Value'])
    df['Result'] = df.groupby('Name').transform(lambda x: x.sum())

    print(df)

    Name Value Result
    0 Name2 1 3
    1 Name2 2 3
    2 Name3 4 4





    share|improve this answer






























      up vote
      0
      down vote













      Df.groupby('Name').apply(lambda x: function (x.value))


      The will work, in x.value you can put your column name






      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',
        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%2f53410178%2fgroupby-and-function-call-in-pandas%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        2
        down vote



        accepted










        Looks like you want a groupby.apply. Something like this should work:



        import pandas as pd

        df = # ... load your data

        def group_sum(g):
        g["Result"] = g["Value"].sum()
        return g

        df_grouped = df.groupby("Name").apply(group_sum)


        Edit: Alexandre Nixon's answer is better for this use case.






        share|improve this answer










        New contributor




        johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






















          up vote
          2
          down vote



          accepted










          Looks like you want a groupby.apply. Something like this should work:



          import pandas as pd

          df = # ... load your data

          def group_sum(g):
          g["Result"] = g["Value"].sum()
          return g

          df_grouped = df.groupby("Name").apply(group_sum)


          Edit: Alexandre Nixon's answer is better for this use case.






          share|improve this answer










          New contributor




          johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




















            up vote
            2
            down vote



            accepted







            up vote
            2
            down vote



            accepted






            Looks like you want a groupby.apply. Something like this should work:



            import pandas as pd

            df = # ... load your data

            def group_sum(g):
            g["Result"] = g["Value"].sum()
            return g

            df_grouped = df.groupby("Name").apply(group_sum)


            Edit: Alexandre Nixon's answer is better for this use case.






            share|improve this answer










            New contributor




            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            Looks like you want a groupby.apply. Something like this should work:



            import pandas as pd

            df = # ... load your data

            def group_sum(g):
            g["Result"] = g["Value"].sum()
            return g

            df_grouped = df.groupby("Name").apply(group_sum)


            Edit: Alexandre Nixon's answer is better for this use case.







            share|improve this answer










            New contributor




            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            share|improve this answer



            share|improve this answer








            edited 2 days ago





















            New contributor




            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            answered 2 days ago









            johnpaton

            23516




            23516




            New contributor




            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





            New contributor





            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            johnpaton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.
























                up vote
                0
                down vote













                You want to use transform for that, which returns a dataframe with the transformed values and the same dimension.



                a['Result'] = a.groupby('Name').transform(lambda x: x.sum())


                For example if you have:



                df = pd.DataFrame({'Name':['Name2','Name2', 'Name3'], 
                'Value':[1,2,4]},
                columns = ['Name','Value'])
                df['Result'] = df.groupby('Name').transform(lambda x: x.sum())

                print(df)

                Name Value Result
                0 Name2 1 3
                1 Name2 2 3
                2 Name3 4 4





                share|improve this answer



























                  up vote
                  0
                  down vote













                  You want to use transform for that, which returns a dataframe with the transformed values and the same dimension.



                  a['Result'] = a.groupby('Name').transform(lambda x: x.sum())


                  For example if you have:



                  df = pd.DataFrame({'Name':['Name2','Name2', 'Name3'], 
                  'Value':[1,2,4]},
                  columns = ['Name','Value'])
                  df['Result'] = df.groupby('Name').transform(lambda x: x.sum())

                  print(df)

                  Name Value Result
                  0 Name2 1 3
                  1 Name2 2 3
                  2 Name3 4 4





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    You want to use transform for that, which returns a dataframe with the transformed values and the same dimension.



                    a['Result'] = a.groupby('Name').transform(lambda x: x.sum())


                    For example if you have:



                    df = pd.DataFrame({'Name':['Name2','Name2', 'Name3'], 
                    'Value':[1,2,4]},
                    columns = ['Name','Value'])
                    df['Result'] = df.groupby('Name').transform(lambda x: x.sum())

                    print(df)

                    Name Value Result
                    0 Name2 1 3
                    1 Name2 2 3
                    2 Name3 4 4





                    share|improve this answer














                    You want to use transform for that, which returns a dataframe with the transformed values and the same dimension.



                    a['Result'] = a.groupby('Name').transform(lambda x: x.sum())


                    For example if you have:



                    df = pd.DataFrame({'Name':['Name2','Name2', 'Name3'], 
                    'Value':[1,2,4]},
                    columns = ['Name','Value'])
                    df['Result'] = df.groupby('Name').transform(lambda x: x.sum())

                    print(df)

                    Name Value Result
                    0 Name2 1 3
                    1 Name2 2 3
                    2 Name3 4 4






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 2 days ago

























                    answered 2 days ago









                    nixon

                    83116




                    83116






















                        up vote
                        0
                        down vote













                        Df.groupby('Name').apply(lambda x: function (x.value))


                        The will work, in x.value you can put your column name






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          Df.groupby('Name').apply(lambda x: function (x.value))


                          The will work, in x.value you can put your column name






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Df.groupby('Name').apply(lambda x: function (x.value))


                            The will work, in x.value you can put your column name






                            share|improve this answer












                            Df.groupby('Name').apply(lambda x: function (x.value))


                            The will work, in x.value you can put your column name







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 2 days ago









                            id101112

                            167115




                            167115






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410178%2fgroupby-and-function-call-in-pandas%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

                                Contact image not getting when fetch all contact list from iPhone by CNContact

                                count number of partitions of a set with n elements into k subsets

                                A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks