如何计算数据框行的标准差? [英] How I can calculate standard deviation for rows of a dataframe?

查看:253
本文介绍了如何计算数据框行的标准差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这对于获取列的std有用:

This is working for getting std for a column:

numpy.std(df['A'])

我想对行做同样的事情

推荐答案

您可以使用

You can use DataFrame.std, which omit non numeric columns:

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

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

If need select only some numeric columns, use subset:

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

numpy.std 有所不同默认情况下,参数ddof(自由度增量):

  • 默认情况下为ddof=1
  • 默认为numpy ddof=0
  • pandas by default ddof=1
  • numpy by default 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

但是您可以很容易地更改它:

But you can change it very easy:

#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   

这篇关于如何计算数据框行的标准差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆