Pandas groupby agg std NaN
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
add a comment |
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
add a comment |
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
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
python pandas std nan pandas-groupby
edited Nov 15 '18 at 0:13
jpp
101k2163112
101k2163112
asked May 12 '18 at 13:48
Alex JAlex J
211
211
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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)
Thanks for your answer! When I change the code to.agg('size','sum','mean',np.std), the outputs still keep NaN. But when I uselambda 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
add a comment |
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.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)
Thanks for your answer! When I change the code to.agg('size','sum','mean',np.std), the outputs still keep NaN. But when I uselambda 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
add a comment |
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)
Thanks for your answer! When I change the code to.agg('size','sum','mean',np.std), the outputs still keep NaN. But when I uselambda 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
add a comment |
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)
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)
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 uselambda 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
add a comment |
Thanks for your answer! When I change the code to.agg('size','sum','mean',np.std), the outputs still keep NaN. But when I uselambda 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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jul 24 '18 at 2:01
etudiantetudiant
1
1
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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