天天看点

python计算列表标准差_python – 如何计算数据帧行的标准差?

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:

numpy.std(df['A'])

我想对行做同样的事情

最佳答案 您可以使用

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

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

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