如何计算数据帧行的标准差?

Nam*_*ena 3 python numpy pandas

df:  

name   group   S1   S2  S3        
A      mn      1    2   8         
B      mn      4    3   5        
C      kl      5    8   2        
D      kl      6    5   5         
E      fh      7    1   3         

output: 

std (S1,S2,S3)
3.78
1
3
0.57
3.05
Run Code Online (Sandbox Code Playgroud)

这是为了获取列的std:

numpy.std(df['A'])
Run Code Online (Sandbox Code Playgroud)

我想对行做同样的事情

jez*_*ael 9

您可以使用DataFrame.std,省略非数字列:

print (df.std())
S1    2.302173
S2    2.774887
S3    2.302173
dtype: float64
Run Code Online (Sandbox Code Playgroud)

如果需要std按列:

print (df.std(axis=1))
0    3.785939
1    1.000000
2    3.000000
3    0.577350
4    3.055050
dtype: float64
Run Code Online (Sandbox Code Playgroud)

如果需要只选择一些数字列,请使用子集:

print (df[['S1','S2']].std())
S1    2.302173
S2    2.774887
dtype: float64
Run Code Online (Sandbox Code Playgroud)

numpy.std默认参数ddof(Delta Degrees of Freedom)有不同的:

  • 大熊猫默认情况下 ddof=1
  • numpy默认 ddof=0

所以有不同的输出:

#ddof=1
print (df.std(axis=1))
0    3.785939
1    1.000000
2    3.000000
3    0.577350
4    3.055050
dtype: float64

#ddof=0
print (np.std(df, axis=1))
0    3.091206
1    0.816497
2    2.449490
3    0.471405
4    2.494438
dtype: float64
Run Code Online (Sandbox Code Playgroud)

但你可以很容易地改变它:

#same output as pandas function
print (np.std(df, ddof=1, axis=1))
0    3.785939
1    1.000000
2    3.000000
3    0.577350
4    3.055050
dtype: float64

#same output as numpy function
print (df.std(ddof=0, axis=1))
0    3.091206
1    0.816497
2    2.449490
3    0.471405
4    2.494438
dtype: float64   
Run Code Online (Sandbox Code Playgroud)