Pandas groupby agg std NaN












4















Inputs:



df['PopEst']
.astype('float')
.groupby(ContinentDict)
.agg(['size','sum','mean','std']))


Outputs:



            size            sum                mean              std
Asia 5 2.898666e+09 5.797333e+08 6.790979e+08
Australia 1 2.331602e+07 2.331602e+07 NaN
Europe 6 4.579297e+08 7.632161e+07 3.464767e+07
North America 2 3.528552e+08 1.764276e+08 1.996696e+08
South America 1 2.059153e+08 2.059153e+08 NaN


Some values in column of std turns out to be NaN if the group just have one row, but I think these values are supposed to be 0, why is that?










share|improve this question





























    4















    Inputs:



    df['PopEst']
    .astype('float')
    .groupby(ContinentDict)
    .agg(['size','sum','mean','std']))


    Outputs:



                size            sum                mean              std
    Asia 5 2.898666e+09 5.797333e+08 6.790979e+08
    Australia 1 2.331602e+07 2.331602e+07 NaN
    Europe 6 4.579297e+08 7.632161e+07 3.464767e+07
    North America 2 3.528552e+08 1.764276e+08 1.996696e+08
    South America 1 2.059153e+08 2.059153e+08 NaN


    Some values in column of std turns out to be NaN if the group just have one row, but I think these values are supposed to be 0, why is that?










    share|improve this question



























      4












      4








      4








      Inputs:



      df['PopEst']
      .astype('float')
      .groupby(ContinentDict)
      .agg(['size','sum','mean','std']))


      Outputs:



                  size            sum                mean              std
      Asia 5 2.898666e+09 5.797333e+08 6.790979e+08
      Australia 1 2.331602e+07 2.331602e+07 NaN
      Europe 6 4.579297e+08 7.632161e+07 3.464767e+07
      North America 2 3.528552e+08 1.764276e+08 1.996696e+08
      South America 1 2.059153e+08 2.059153e+08 NaN


      Some values in column of std turns out to be NaN if the group just have one row, but I think these values are supposed to be 0, why is that?










      share|improve this question
















      Inputs:



      df['PopEst']
      .astype('float')
      .groupby(ContinentDict)
      .agg(['size','sum','mean','std']))


      Outputs:



                  size            sum                mean              std
      Asia 5 2.898666e+09 5.797333e+08 6.790979e+08
      Australia 1 2.331602e+07 2.331602e+07 NaN
      Europe 6 4.579297e+08 7.632161e+07 3.464767e+07
      North America 2 3.528552e+08 1.764276e+08 1.996696e+08
      South America 1 2.059153e+08 2.059153e+08 NaN


      Some values in column of std turns out to be NaN if the group just have one row, but I think these values are supposed to be 0, why is that?







      python pandas std nan pandas-groupby






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 0:13









      jpp

      101k2163112




      101k2163112










      asked May 12 '18 at 13:48









      Alex JAlex J

      211




      211
























          2 Answers
          2






          active

          oldest

          votes


















          2














          pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number.



          numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number.



          To understand the difference between sample and population, see Bessel's correction.



          Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example.



          import pandas as pd, numpy as np

          df = pd.DataFrame(np.random.randint(0, 9, (5, 2)))

          def std(x): return np.std(x)

          res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std])

          print(res)

          size sum mean std
          0
          0 2 13 6.5 0.5
          4 1 3 3.0 0.0
          5 1 3 3.0 0.0
          6 1 3 3.0 0.0


          Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0:



          res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)





          share|improve this answer


























          • Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

            – Alex J
            May 13 '18 at 7:27





















          0














          According to the document, np.std(..., ddof=1) by default set "delta degree of freedom" to 1. To fix your problem, simply replace np.std with lambda x: np.std(x, ddof=0) then your NaN will be changed to 0.






          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%2f50306914%2fpandas-groupby-agg-std-nan%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









            2














            pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number.



            numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number.



            To understand the difference between sample and population, see Bessel's correction.



            Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example.



            import pandas as pd, numpy as np

            df = pd.DataFrame(np.random.randint(0, 9, (5, 2)))

            def std(x): return np.std(x)

            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std])

            print(res)

            size sum mean std
            0
            0 2 13 6.5 0.5
            4 1 3 3.0 0.0
            5 1 3 3.0 0.0
            6 1 3 3.0 0.0


            Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0:



            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)





            share|improve this answer


























            • Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

              – Alex J
              May 13 '18 at 7:27


















            2














            pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number.



            numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number.



            To understand the difference between sample and population, see Bessel's correction.



            Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example.



            import pandas as pd, numpy as np

            df = pd.DataFrame(np.random.randint(0, 9, (5, 2)))

            def std(x): return np.std(x)

            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std])

            print(res)

            size sum mean std
            0
            0 2 13 6.5 0.5
            4 1 3 3.0 0.0
            5 1 3 3.0 0.0
            6 1 3 3.0 0.0


            Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0:



            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)





            share|improve this answer


























            • Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

              – Alex J
              May 13 '18 at 7:27
















            2












            2








            2







            pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number.



            numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number.



            To understand the difference between sample and population, see Bessel's correction.



            Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example.



            import pandas as pd, numpy as np

            df = pd.DataFrame(np.random.randint(0, 9, (5, 2)))

            def std(x): return np.std(x)

            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std])

            print(res)

            size sum mean std
            0
            0 2 13 6.5 0.5
            4 1 3 3.0 0.0
            5 1 3 3.0 0.0
            6 1 3 3.0 0.0


            Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0:



            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)





            share|improve this answer















            pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number.



            numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number.



            To understand the difference between sample and population, see Bessel's correction.



            Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example.



            import pandas as pd, numpy as np

            df = pd.DataFrame(np.random.randint(0, 9, (5, 2)))

            def std(x): return np.std(x)

            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std])

            print(res)

            size sum mean std
            0
            0 2 13 6.5 0.5
            4 1 3 3.0 0.0
            5 1 3 3.0 0.0
            6 1 3 3.0 0.0


            Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0:



            res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 12 '18 at 14:25

























            answered May 12 '18 at 14:08









            jppjpp

            101k2163112




            101k2163112













            • Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

              – Alex J
              May 13 '18 at 7:27





















            • Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

              – Alex J
              May 13 '18 at 7:27



















            Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

            – Alex J
            May 13 '18 at 7:27







            Thanks for your answer! When I change the code to .agg('size','sum','mean',np.std), the outputs still keep NaN. But when I use lambda x:np.std(x) instead, NaNs turn to 0, it is what I wanted. I wonder know why this happened.

            – Alex J
            May 13 '18 at 7:27















            0














            According to the document, np.std(..., ddof=1) by default set "delta degree of freedom" to 1. To fix your problem, simply replace np.std with lambda x: np.std(x, ddof=0) then your NaN will be changed to 0.






            share|improve this answer




























              0














              According to the document, np.std(..., ddof=1) by default set "delta degree of freedom" to 1. To fix your problem, simply replace np.std with lambda x: np.std(x, ddof=0) then your NaN will be changed to 0.






              share|improve this answer


























                0












                0








                0







                According to the document, np.std(..., ddof=1) by default set "delta degree of freedom" to 1. To fix your problem, simply replace np.std with lambda x: np.std(x, ddof=0) then your NaN will be changed to 0.






                share|improve this answer













                According to the document, np.std(..., ddof=1) by default set "delta degree of freedom" to 1. To fix your problem, simply replace np.std with lambda x: np.std(x, ddof=0) then your NaN will be changed to 0.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 24 '18 at 2:01









                etudiantetudiant

                1




                1






























                    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%2f50306914%2fpandas-groupby-agg-std-nan%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

                    List item for chat from Array inside array React Native

                    Thiostrepton

                    Caerphilly