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

7
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

以下是获取一列标准差的有效方法:

numpy.std(df['A'])

我希望对于行也能做同样的操作。


2
df.std() 应该可以满足你的需求。 - EdChum
2个回答

20
您可以使用DataFrame.std函数,该函数会忽略非数值列:
print (df.std())
S1    2.302173
S2    2.774887
S3    2.302173
dtype: float64

如果需要按列使用std

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

如果需要仅选择一些数字列,请使用subset:

print (df[['S1','S2']].std())
S1    2.302173
S2    2.774887
dtype: float64

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

  • pandas默认为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

但您可以非常轻松地更改它:

#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   

0

当你无法在行上执行与列相同的操作时,可以使用“转置”

np.std( df.transpose()['S1'] )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接