Pandas: groupby to sum subsets of columns











up vote
0
down vote

favorite












I have a pandas dataframe with multiple columns. I would like to calculate the sum of various subsets of this columns and assign a name to each group of columns.



Is it possible to achieve this using groupby or other pandas methods?



Setup:



import numpy as np; np.random.seed(1)
import pandas as pd

df = pd.DataFrame(np.random.randint(0, 10, (3, 5)), columns=['A', 'B', 'C', 'D', 'E'])

columns_groups = {'First': ['A', 'B', 'C'],
'Second': ['D', 'E'],
'Some': ['A', 'C', 'D'],
'All': ['A', 'B', 'C', 'D', 'E']}


Desired output: (is there a more elegant solution?)



out = {}
for name, group in columns_groups.items():
out[name] = df[group].sum(axis=1)

out = pd.DataFrame(out)

out
Out[22]:
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9


My attempt:



df.groupby(columns_groups, axis=1).sum(axis=1)

Out[21]:
Empty DataFrame
Columns:
Index: [0, 1, 2]









share|improve this question
























  • P.s. suggestions for a better title are welcome
    – FLab
    Nov 22 at 15:40










  • Any reason you're specifically after a groupby method?
    – Jon Clements
    Nov 22 at 15:49










  • I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
    – FLab
    Nov 22 at 16:01










  • I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
    – user3471881
    Nov 22 at 17:13

















up vote
0
down vote

favorite












I have a pandas dataframe with multiple columns. I would like to calculate the sum of various subsets of this columns and assign a name to each group of columns.



Is it possible to achieve this using groupby or other pandas methods?



Setup:



import numpy as np; np.random.seed(1)
import pandas as pd

df = pd.DataFrame(np.random.randint(0, 10, (3, 5)), columns=['A', 'B', 'C', 'D', 'E'])

columns_groups = {'First': ['A', 'B', 'C'],
'Second': ['D', 'E'],
'Some': ['A', 'C', 'D'],
'All': ['A', 'B', 'C', 'D', 'E']}


Desired output: (is there a more elegant solution?)



out = {}
for name, group in columns_groups.items():
out[name] = df[group].sum(axis=1)

out = pd.DataFrame(out)

out
Out[22]:
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9


My attempt:



df.groupby(columns_groups, axis=1).sum(axis=1)

Out[21]:
Empty DataFrame
Columns:
Index: [0, 1, 2]









share|improve this question
























  • P.s. suggestions for a better title are welcome
    – FLab
    Nov 22 at 15:40










  • Any reason you're specifically after a groupby method?
    – Jon Clements
    Nov 22 at 15:49










  • I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
    – FLab
    Nov 22 at 16:01










  • I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
    – user3471881
    Nov 22 at 17:13















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a pandas dataframe with multiple columns. I would like to calculate the sum of various subsets of this columns and assign a name to each group of columns.



Is it possible to achieve this using groupby or other pandas methods?



Setup:



import numpy as np; np.random.seed(1)
import pandas as pd

df = pd.DataFrame(np.random.randint(0, 10, (3, 5)), columns=['A', 'B', 'C', 'D', 'E'])

columns_groups = {'First': ['A', 'B', 'C'],
'Second': ['D', 'E'],
'Some': ['A', 'C', 'D'],
'All': ['A', 'B', 'C', 'D', 'E']}


Desired output: (is there a more elegant solution?)



out = {}
for name, group in columns_groups.items():
out[name] = df[group].sum(axis=1)

out = pd.DataFrame(out)

out
Out[22]:
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9


My attempt:



df.groupby(columns_groups, axis=1).sum(axis=1)

Out[21]:
Empty DataFrame
Columns:
Index: [0, 1, 2]









share|improve this question















I have a pandas dataframe with multiple columns. I would like to calculate the sum of various subsets of this columns and assign a name to each group of columns.



Is it possible to achieve this using groupby or other pandas methods?



Setup:



import numpy as np; np.random.seed(1)
import pandas as pd

df = pd.DataFrame(np.random.randint(0, 10, (3, 5)), columns=['A', 'B', 'C', 'D', 'E'])

columns_groups = {'First': ['A', 'B', 'C'],
'Second': ['D', 'E'],
'Some': ['A', 'C', 'D'],
'All': ['A', 'B', 'C', 'D', 'E']}


Desired output: (is there a more elegant solution?)



out = {}
for name, group in columns_groups.items():
out[name] = df[group].sum(axis=1)

out = pd.DataFrame(out)

out
Out[22]:
All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9


My attempt:



df.groupby(columns_groups, axis=1).sum(axis=1)

Out[21]:
Empty DataFrame
Columns:
Index: [0, 1, 2]






python pandas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 16:01

























asked Nov 22 at 15:39









FLab

3,5431941




3,5431941












  • P.s. suggestions for a better title are welcome
    – FLab
    Nov 22 at 15:40










  • Any reason you're specifically after a groupby method?
    – Jon Clements
    Nov 22 at 15:49










  • I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
    – FLab
    Nov 22 at 16:01










  • I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
    – user3471881
    Nov 22 at 17:13




















  • P.s. suggestions for a better title are welcome
    – FLab
    Nov 22 at 15:40










  • Any reason you're specifically after a groupby method?
    – Jon Clements
    Nov 22 at 15:49










  • I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
    – FLab
    Nov 22 at 16:01










  • I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
    – user3471881
    Nov 22 at 17:13


















P.s. suggestions for a better title are welcome
– FLab
Nov 22 at 15:40




P.s. suggestions for a better title are welcome
– FLab
Nov 22 at 15:40












Any reason you're specifically after a groupby method?
– Jon Clements
Nov 22 at 15:49




Any reason you're specifically after a groupby method?
– Jon Clements
Nov 22 at 15:49












I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
– FLab
Nov 22 at 16:01




I "feel" like this case might be covered by groupby, so I'd like to know more about its syntax or other pandas methods
– FLab
Nov 22 at 16:01












I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
– user3471881
Nov 22 at 17:13






I really like the idea of using a dictionary like this to groupby but unfortunately it is not possible afaik. If we df.transpose() we could technically use df.groupby(dictionary) to group by index and name our groups, but then key has to be the value in index and value the name of our group. This obv wont work in this case since the index will occur multiple times in different groups. Would be a cool feature though (to be able to do it on your kind of dict) :D
– user3471881
Nov 22 at 17:13














2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










Just a different and fun way , using reindex with MultiIndex



df=df.reindex(columns=sum(columns_groups.values(),))
t=[(x,z ) for x , y in columns_groups.items() for z in y]
df.columns=pd.MultiIndex.from_tuples(t)
df.sum(level=0,axis=1)
First Second Some All
0 22 8 18 30
1 17 9 16 26
2 6 15 14 21





share|improve this answer

















  • 1




    Not planning to use it in my code, but it does indeed give a 'group-by' like solution
    – FLab
    Dec 5 at 17:41


















up vote
1
down vote













Is this okay with you:



pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})

All First Second Some
0 27 22 5 19
1 23 8 15 13
2 17 11 6 9


It's same what you did, only in comprehension.






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%2f53434296%2fpandas-groupby-to-sum-subsets-of-columns%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








    up vote
    1
    down vote



    accepted










    Just a different and fun way , using reindex with MultiIndex



    df=df.reindex(columns=sum(columns_groups.values(),))
    t=[(x,z ) for x , y in columns_groups.items() for z in y]
    df.columns=pd.MultiIndex.from_tuples(t)
    df.sum(level=0,axis=1)
    First Second Some All
    0 22 8 18 30
    1 17 9 16 26
    2 6 15 14 21





    share|improve this answer

















    • 1




      Not planning to use it in my code, but it does indeed give a 'group-by' like solution
      – FLab
      Dec 5 at 17:41















    up vote
    1
    down vote



    accepted










    Just a different and fun way , using reindex with MultiIndex



    df=df.reindex(columns=sum(columns_groups.values(),))
    t=[(x,z ) for x , y in columns_groups.items() for z in y]
    df.columns=pd.MultiIndex.from_tuples(t)
    df.sum(level=0,axis=1)
    First Second Some All
    0 22 8 18 30
    1 17 9 16 26
    2 6 15 14 21





    share|improve this answer

















    • 1




      Not planning to use it in my code, but it does indeed give a 'group-by' like solution
      – FLab
      Dec 5 at 17:41













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    Just a different and fun way , using reindex with MultiIndex



    df=df.reindex(columns=sum(columns_groups.values(),))
    t=[(x,z ) for x , y in columns_groups.items() for z in y]
    df.columns=pd.MultiIndex.from_tuples(t)
    df.sum(level=0,axis=1)
    First Second Some All
    0 22 8 18 30
    1 17 9 16 26
    2 6 15 14 21





    share|improve this answer












    Just a different and fun way , using reindex with MultiIndex



    df=df.reindex(columns=sum(columns_groups.values(),))
    t=[(x,z ) for x , y in columns_groups.items() for z in y]
    df.columns=pd.MultiIndex.from_tuples(t)
    df.sum(level=0,axis=1)
    First Second Some All
    0 22 8 18 30
    1 17 9 16 26
    2 6 15 14 21






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 at 16:04









    W-B

    97.3k73162




    97.3k73162








    • 1




      Not planning to use it in my code, but it does indeed give a 'group-by' like solution
      – FLab
      Dec 5 at 17:41














    • 1




      Not planning to use it in my code, but it does indeed give a 'group-by' like solution
      – FLab
      Dec 5 at 17:41








    1




    1




    Not planning to use it in my code, but it does indeed give a 'group-by' like solution
    – FLab
    Dec 5 at 17:41




    Not planning to use it in my code, but it does indeed give a 'group-by' like solution
    – FLab
    Dec 5 at 17:41












    up vote
    1
    down vote













    Is this okay with you:



    pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})

    All First Second Some
    0 27 22 5 19
    1 23 8 15 13
    2 17 11 6 9


    It's same what you did, only in comprehension.






    share|improve this answer

























      up vote
      1
      down vote













      Is this okay with you:



      pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})

      All First Second Some
      0 27 22 5 19
      1 23 8 15 13
      2 17 11 6 9


      It's same what you did, only in comprehension.






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        Is this okay with you:



        pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})

        All First Second Some
        0 27 22 5 19
        1 23 8 15 13
        2 17 11 6 9


        It's same what you did, only in comprehension.






        share|improve this answer












        Is this okay with you:



        pd.DataFrame({k: df[v].sum(axis=1) for k, v in columns_groups.items()})

        All First Second Some
        0 27 22 5 19
        1 23 8 15 13
        2 17 11 6 9


        It's same what you did, only in comprehension.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 at 15:46









        zipa

        15.8k21435




        15.8k21435






























            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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • 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%2f53434296%2fpandas-groupby-to-sum-subsets-of-columns%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

            Trompette piccolo

            Slow SSRS Report in dynamic grouping and multiple parameters

            Simon Yates (cyclisme)