Groupby() in pandas in PythonCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Does Python have a string 'contains' substring method?Renaming columns in pandas“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandas

Christian apologetics regarding the killing of innocent children during the Genesis flood

Ex-contractor published company source code and secrets online

Y2K... in 2019?

Is it incorrect to write "I rate this book a 3 out of 4 stars?"

Help evaluating integral (anything simple that I am missing?)

English - Acceptable use of parentheses in an author's name

Who are these characters/superheroes in the posters from Chris's room in Family Guy?

Author changing name

Why is transplanting a specific intact brain impossible if it is generally possible?

Team goes to lunch frequently, I do intermittent fasting but still want to socialize

I accidentally overwrote a Linux binary file

Wherein the Shatapatha Brahmana it was mentioned about 8.64 lakh alphabets in Vedas?

How should an administrative assistant reply to student addressing them as "Professor" or "Doctor"?

Dropdowns & Chevrons for Right to Left languages

How does "Te vas a cansar" mean "You're going to get tired"?

Identification of vintage sloping window

Bitcoin successfully deducted on sender wallet but did not reach receiver wallet

A tool to replace all words with antonyms

How can you evade tax by getting employment income just in equity, then using this equity as collateral to take out loan?

What is the difference between 型 and 形?

Why does Intel's Haswell chip allow FP multiplication to be twice as fast as addition?

First amendment and employment: Can a police department terminate an officer for speech?

In a topological space if there exists a loop that cannot be contracted to a point does there exist a simple loop that cannot be contracted also?

Withdrew when Jimmy met up with Heath



Groupby() in pandas in Python


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Does Python have a string 'contains' substring method?Renaming columns in pandas“Large data” work flows using pandasSelect rows from a DataFrame based on values in a column in pandas






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








0















I have a dataset with the following columns:




Country, Year, Population, Suicide case, Country GDP




Problem: I Want to calculate (Suicide case / Population )*100 for each country



My Approach :



import pandas as pd
fileName = pd.read_csv("File Path")
pd.groupby("Country")


How should I extend my code for the calculation above?










share|improve this question
































    0















    I have a dataset with the following columns:




    Country, Year, Population, Suicide case, Country GDP




    Problem: I Want to calculate (Suicide case / Population )*100 for each country



    My Approach :



    import pandas as pd
    fileName = pd.read_csv("File Path")
    pd.groupby("Country")


    How should I extend my code for the calculation above?










    share|improve this question




























      0












      0








      0








      I have a dataset with the following columns:




      Country, Year, Population, Suicide case, Country GDP




      Problem: I Want to calculate (Suicide case / Population )*100 for each country



      My Approach :



      import pandas as pd
      fileName = pd.read_csv("File Path")
      pd.groupby("Country")


      How should I extend my code for the calculation above?










      share|improve this question
















      I have a dataset with the following columns:




      Country, Year, Population, Suicide case, Country GDP




      Problem: I Want to calculate (Suicide case / Population )*100 for each country



      My Approach :



      import pandas as pd
      fileName = pd.read_csv("File Path")
      pd.groupby("Country")


      How should I extend my code for the calculation above?







      python pandas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 9:03









      Sreekiran

      1,1401 gold badge4 silver badges21 bronze badges




      1,1401 gold badge4 silver badges21 bronze badges










      asked Mar 27 at 8:26









      Soma AnchalSoma Anchal

      225 bronze badges




      225 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          2














          Here you have with an example. May be it could be better, but this should work for you.



          import pandas as pd
          df = pd.DataFrame("Country":["France", "UK", "France", "UK"],
          "Population":[1, 2, 3, 4],
          "Suicide case":[5, 3, 6, 2])
          df_grouped = df.groupby("Country").sum()
          (df_grouped["Suicide case"]/df_grouped["Population"])*100





          share|improve this answer
































            2














            Also a more concise one is:



            df.groupby('Country').apply(lambda x: x['Suicide case'].sum()/
            float(x['Population'].sum())*100)





            share|improve this answer
































              1














              If I understood your question correctly then you can try below code to get your desired result:



              fileName = fileName.groupby(['Year','Country']).sum()
              fileName['New_var'] = (fileName['Suicide case']/ fileName['Population'])*100


              you also need to the year in the group otherwise year-wise will also get aggregate.






              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%2f55372667%2fgroupby-in-pandas-in-python%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









                2














                Here you have with an example. May be it could be better, but this should work for you.



                import pandas as pd
                df = pd.DataFrame("Country":["France", "UK", "France", "UK"],
                "Population":[1, 2, 3, 4],
                "Suicide case":[5, 3, 6, 2])
                df_grouped = df.groupby("Country").sum()
                (df_grouped["Suicide case"]/df_grouped["Population"])*100





                share|improve this answer





























                  2














                  Here you have with an example. May be it could be better, but this should work for you.



                  import pandas as pd
                  df = pd.DataFrame("Country":["France", "UK", "France", "UK"],
                  "Population":[1, 2, 3, 4],
                  "Suicide case":[5, 3, 6, 2])
                  df_grouped = df.groupby("Country").sum()
                  (df_grouped["Suicide case"]/df_grouped["Population"])*100





                  share|improve this answer



























                    2












                    2








                    2







                    Here you have with an example. May be it could be better, but this should work for you.



                    import pandas as pd
                    df = pd.DataFrame("Country":["France", "UK", "France", "UK"],
                    "Population":[1, 2, 3, 4],
                    "Suicide case":[5, 3, 6, 2])
                    df_grouped = df.groupby("Country").sum()
                    (df_grouped["Suicide case"]/df_grouped["Population"])*100





                    share|improve this answer













                    Here you have with an example. May be it could be better, but this should work for you.



                    import pandas as pd
                    df = pd.DataFrame("Country":["France", "UK", "France", "UK"],
                    "Population":[1, 2, 3, 4],
                    "Suicide case":[5, 3, 6, 2])
                    df_grouped = df.groupby("Country").sum()
                    (df_grouped["Suicide case"]/df_grouped["Population"])*100






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 8:58









                    AngeloAngelo

                    18113 bronze badges




                    18113 bronze badges


























                        2














                        Also a more concise one is:



                        df.groupby('Country').apply(lambda x: x['Suicide case'].sum()/
                        float(x['Population'].sum())*100)





                        share|improve this answer





























                          2














                          Also a more concise one is:



                          df.groupby('Country').apply(lambda x: x['Suicide case'].sum()/
                          float(x['Population'].sum())*100)





                          share|improve this answer



























                            2












                            2








                            2







                            Also a more concise one is:



                            df.groupby('Country').apply(lambda x: x['Suicide case'].sum()/
                            float(x['Population'].sum())*100)





                            share|improve this answer













                            Also a more concise one is:



                            df.groupby('Country').apply(lambda x: x['Suicide case'].sum()/
                            float(x['Population'].sum())*100)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 27 at 9:52









                            LoochieLoochie

                            1,0363 silver badges11 bronze badges




                            1,0363 silver badges11 bronze badges
























                                1














                                If I understood your question correctly then you can try below code to get your desired result:



                                fileName = fileName.groupby(['Year','Country']).sum()
                                fileName['New_var'] = (fileName['Suicide case']/ fileName['Population'])*100


                                you also need to the year in the group otherwise year-wise will also get aggregate.






                                share|improve this answer





























                                  1














                                  If I understood your question correctly then you can try below code to get your desired result:



                                  fileName = fileName.groupby(['Year','Country']).sum()
                                  fileName['New_var'] = (fileName['Suicide case']/ fileName['Population'])*100


                                  you also need to the year in the group otherwise year-wise will also get aggregate.






                                  share|improve this answer



























                                    1












                                    1








                                    1







                                    If I understood your question correctly then you can try below code to get your desired result:



                                    fileName = fileName.groupby(['Year','Country']).sum()
                                    fileName['New_var'] = (fileName['Suicide case']/ fileName['Population'])*100


                                    you also need to the year in the group otherwise year-wise will also get aggregate.






                                    share|improve this answer













                                    If I understood your question correctly then you can try below code to get your desired result:



                                    fileName = fileName.groupby(['Year','Country']).sum()
                                    fileName['New_var'] = (fileName['Suicide case']/ fileName['Population'])*100


                                    you also need to the year in the group otherwise year-wise will also get aggregate.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 27 at 9:32









                                    Ghanshyam SavaliyaGhanshyam Savaliya

                                    16311 bronze badges




                                    16311 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%2f55372667%2fgroupby-in-pandas-in-python%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