Pandas: How to sum a variable by group? The Next CEO of Stack OverflowPandas group-by and sumHow to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?Using global variables in a functionHow do I pass a variable by reference?How do I list all files of a directory?Renaming columns in pandas“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

Incomplete cube

MT "will strike" & LXX "will watch carefully" (Gen 3:15)?

My boss doesn't want me to have a side project

Man transported from Alternate World into ours by a Neutrino Detector

Mathematica command that allows it to read my intentions

How seriously should I take size and weight limits of hand luggage?

Do I need to write [sic] when including a quotation with a number less than 10 that isn't written out?

How to coordinate airplane tickets?

Strange use of "whether ... than ..." in official text

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

Can I cast Thunderwave and be at the center of its bottom face, but not be affected by it?

Free fall ellipse or parabola?

How can a day be of 24 hours?

How should I connect my cat5 cable to connectors having an orange-green line?

Is it correct to say moon starry nights?

Find the majority element, which appears more than half the time

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

How can I separate the number from the unit in argument?

Why can't we say "I have been having a dog"?

Is the offspring between a demon and a celestial possible? If so what is it called and is it in a book somewhere?

What does this strange code stamp on my passport mean?

Is a distribution that is normal, but highly skewed, considered Gaussian?

What is the difference between 'contrib' and 'non-free' packages repositories?

That's an odd coin - I wonder why



Pandas: How to sum a variable by group?



The Next CEO of Stack OverflowPandas group-by and sumHow to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?Using global variables in a functionHow do I pass a variable by reference?How do I list all files of a directory?Renaming columns in pandas“Large data” work flows using pandasHow to iterate over rows in a DataFrame in Pandas?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?










1















I would like to sum multiple values to one in python.
See the picture below of my data. I want to sum all the values of AGE for each year for each country.



Instead of having this:



country TIME AGE Value
A 2017 20-60 200
A 2017 60-80 100
A 2016 20-60 200
A 2016 60-80 200
B 2017 20-60 300
B 2017 60-80 300
B 2016 20-60 400
B 2016 60-80 400


I would like to have this:



country TIME Value
A 2017 300
A 2016 400
B 2017 600
B 2016 800


The types of data:



df4types
AGE object
Value object
dtype: object


The data has a multi index by country and TIME.



If have tried this:



df=df.groupby(by=["TIME","GEO"])['Value'].sum()


and this:



df=df.groupby(by=["TIME","GEO"]).sum()['Value']


Both "worked" but result in an enormous value. Like it doesn't sum but paste the numbers behind each other. I have tried to change the variable type to numeric by using:
by df.Value.astype(float) & df.Value.astype(int)



Unfortunately this didn't solve the problem. Does someone have an idea how to sum the values by group and time correctly? I have also uploaded a picture of the real dataset.



enter image description here










share|improve this question
























  • Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

    – Leonid
    Mar 21 at 20:05






  • 1





    df.Value = df.Value.astype(int) then run your code again

    – RafaelC
    Mar 21 at 20:06






  • 1





    You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

    – RafaelC
    Mar 21 at 20:07












  • What is GEO is groupby?

    – Rarblack
    Mar 21 at 20:10















1















I would like to sum multiple values to one in python.
See the picture below of my data. I want to sum all the values of AGE for each year for each country.



Instead of having this:



country TIME AGE Value
A 2017 20-60 200
A 2017 60-80 100
A 2016 20-60 200
A 2016 60-80 200
B 2017 20-60 300
B 2017 60-80 300
B 2016 20-60 400
B 2016 60-80 400


I would like to have this:



country TIME Value
A 2017 300
A 2016 400
B 2017 600
B 2016 800


The types of data:



df4types
AGE object
Value object
dtype: object


The data has a multi index by country and TIME.



If have tried this:



df=df.groupby(by=["TIME","GEO"])['Value'].sum()


and this:



df=df.groupby(by=["TIME","GEO"]).sum()['Value']


Both "worked" but result in an enormous value. Like it doesn't sum but paste the numbers behind each other. I have tried to change the variable type to numeric by using:
by df.Value.astype(float) & df.Value.astype(int)



Unfortunately this didn't solve the problem. Does someone have an idea how to sum the values by group and time correctly? I have also uploaded a picture of the real dataset.



enter image description here










share|improve this question
























  • Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

    – Leonid
    Mar 21 at 20:05






  • 1





    df.Value = df.Value.astype(int) then run your code again

    – RafaelC
    Mar 21 at 20:06






  • 1





    You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

    – RafaelC
    Mar 21 at 20:07












  • What is GEO is groupby?

    – Rarblack
    Mar 21 at 20:10













1












1








1








I would like to sum multiple values to one in python.
See the picture below of my data. I want to sum all the values of AGE for each year for each country.



Instead of having this:



country TIME AGE Value
A 2017 20-60 200
A 2017 60-80 100
A 2016 20-60 200
A 2016 60-80 200
B 2017 20-60 300
B 2017 60-80 300
B 2016 20-60 400
B 2016 60-80 400


I would like to have this:



country TIME Value
A 2017 300
A 2016 400
B 2017 600
B 2016 800


The types of data:



df4types
AGE object
Value object
dtype: object


The data has a multi index by country and TIME.



If have tried this:



df=df.groupby(by=["TIME","GEO"])['Value'].sum()


and this:



df=df.groupby(by=["TIME","GEO"]).sum()['Value']


Both "worked" but result in an enormous value. Like it doesn't sum but paste the numbers behind each other. I have tried to change the variable type to numeric by using:
by df.Value.astype(float) & df.Value.astype(int)



Unfortunately this didn't solve the problem. Does someone have an idea how to sum the values by group and time correctly? I have also uploaded a picture of the real dataset.



enter image description here










share|improve this question
















I would like to sum multiple values to one in python.
See the picture below of my data. I want to sum all the values of AGE for each year for each country.



Instead of having this:



country TIME AGE Value
A 2017 20-60 200
A 2017 60-80 100
A 2016 20-60 200
A 2016 60-80 200
B 2017 20-60 300
B 2017 60-80 300
B 2016 20-60 400
B 2016 60-80 400


I would like to have this:



country TIME Value
A 2017 300
A 2016 400
B 2017 600
B 2016 800


The types of data:



df4types
AGE object
Value object
dtype: object


The data has a multi index by country and TIME.



If have tried this:



df=df.groupby(by=["TIME","GEO"])['Value'].sum()


and this:



df=df.groupby(by=["TIME","GEO"]).sum()['Value']


Both "worked" but result in an enormous value. Like it doesn't sum but paste the numbers behind each other. I have tried to change the variable type to numeric by using:
by df.Value.astype(float) & df.Value.astype(int)



Unfortunately this didn't solve the problem. Does someone have an idea how to sum the values by group and time correctly? I have also uploaded a picture of the real dataset.



enter image description here







python pandas pandas-groupby






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 20:13









petezurich

3,76581936




3,76581936










asked Mar 21 at 19:59









PatPat

82




82












  • Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

    – Leonid
    Mar 21 at 20:05






  • 1





    df.Value = df.Value.astype(int) then run your code again

    – RafaelC
    Mar 21 at 20:06






  • 1





    You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

    – RafaelC
    Mar 21 at 20:07












  • What is GEO is groupby?

    – Rarblack
    Mar 21 at 20:10

















  • Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

    – Leonid
    Mar 21 at 20:05






  • 1





    df.Value = df.Value.astype(int) then run your code again

    – RafaelC
    Mar 21 at 20:06






  • 1





    You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

    – RafaelC
    Mar 21 at 20:07












  • What is GEO is groupby?

    – Rarblack
    Mar 21 at 20:10
















Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

– Leonid
Mar 21 at 20:05





Related: stackoverflow.com/questions/39922986/pandas-group-by-and-sum

– Leonid
Mar 21 at 20:05




1




1





df.Value = df.Value.astype(int) then run your code again

– RafaelC
Mar 21 at 20:06





df.Value = df.Value.astype(int) then run your code again

– RafaelC
Mar 21 at 20:06




1




1





You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

– RafaelC
Mar 21 at 20:07






You have strings and not numbers. When you sum, you concatenate the strings. Notice that you have to assign back the result of df.Value.astype(int)

– RafaelC
Mar 21 at 20:07














What is GEO is groupby?

– Rarblack
Mar 21 at 20:10





What is GEO is groupby?

– Rarblack
Mar 21 at 20:10












1 Answer
1






active

oldest

votes


















0














  • The age column doesn't seem to play a role in the data you want.

  • The "Value" shouldn't be a dtype=object. If you try df.Value = df.Value.astype(int) or df.Value=pd.to_numeric(df.Value) and it doesn't work then I'm betting there is some data you will need to clean up in that column)

  • You shouldn't need to mess with the multi index

After you do the above then try this code.



import pandas as pd
df = pd.DataFrame(<your data here>)
result = df.groupby(by=['country','TIME']).sum()





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%2f55288399%2fpandas-how-to-sum-a-variable-by-group%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









    0














    • The age column doesn't seem to play a role in the data you want.

    • The "Value" shouldn't be a dtype=object. If you try df.Value = df.Value.astype(int) or df.Value=pd.to_numeric(df.Value) and it doesn't work then I'm betting there is some data you will need to clean up in that column)

    • You shouldn't need to mess with the multi index

    After you do the above then try this code.



    import pandas as pd
    df = pd.DataFrame(<your data here>)
    result = df.groupby(by=['country','TIME']).sum()





    share|improve this answer



























      0














      • The age column doesn't seem to play a role in the data you want.

      • The "Value" shouldn't be a dtype=object. If you try df.Value = df.Value.astype(int) or df.Value=pd.to_numeric(df.Value) and it doesn't work then I'm betting there is some data you will need to clean up in that column)

      • You shouldn't need to mess with the multi index

      After you do the above then try this code.



      import pandas as pd
      df = pd.DataFrame(<your data here>)
      result = df.groupby(by=['country','TIME']).sum()





      share|improve this answer

























        0












        0








        0







        • The age column doesn't seem to play a role in the data you want.

        • The "Value" shouldn't be a dtype=object. If you try df.Value = df.Value.astype(int) or df.Value=pd.to_numeric(df.Value) and it doesn't work then I'm betting there is some data you will need to clean up in that column)

        • You shouldn't need to mess with the multi index

        After you do the above then try this code.



        import pandas as pd
        df = pd.DataFrame(<your data here>)
        result = df.groupby(by=['country','TIME']).sum()





        share|improve this answer













        • The age column doesn't seem to play a role in the data you want.

        • The "Value" shouldn't be a dtype=object. If you try df.Value = df.Value.astype(int) or df.Value=pd.to_numeric(df.Value) and it doesn't work then I'm betting there is some data you will need to clean up in that column)

        • You shouldn't need to mess with the multi index

        After you do the above then try this code.



        import pandas as pd
        df = pd.DataFrame(<your data here>)
        result = df.groupby(by=['country','TIME']).sum()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 21 at 20:16









        Back2BasicsBack2Basics

        4,63311936




        4,63311936





























            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%2f55288399%2fpandas-how-to-sum-a-variable-by-group%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

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript