luc*_*uke 4 python statistics variance standard-deviation pandas
我正在尝试使用 pandas 求均值、方差和 SD。但手动计算与pandas输出不同。使用 pandas 有什么我想念的吗?附上xl截图供参考
import pandas as pd
dg_df = pd.DataFrame(
data=[600,470,170,430,300],
index=['a','b','c','d','e'])
print(dg_df.mean(axis=0)) # 394.0 matches with manual calculation
print(dg_df.var()) # 27130.0 not matching with manual calculation 21704
print(dg_df.std(axis=0)) # 164.71187 not matching with manual calculation 147.32
Run Code Online (Sandbox Code Playgroud)
标准差有不止一种定义。您正在计算 Excel 的等效项STDEV.P,其描述为:“根据整个总体计算标准差...... ”。如果您需要 Excel 中的样本标准差,请使用STDEV.S.
pd.DataFrame.std默认情况下假定自由度为1 ,也称为样本标准差。
numpy.std默认情况下假定自由度为0 ,也称为总体标准差。
请参阅贝塞尔修正以了解样本和总体之间的差异。
您还可以ddof=0使用 Pandas std/var方法指定:
dg_df.std(ddof=0)
dg_df.var(ddof=0)
Run Code Online (Sandbox Code Playgroud)