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

这篇博客介绍了如何在Python中使用pandas DataFrame计算列和行的标准差。通过`DataFrame.std()`函数可以方便地获取列的标准差,而设置`axis=1`则可以计算行的标准差。还讨论了pandas与numpy在标准差计算中默认的`ddof`(Delta Degrees of Freedom)参数差异,并展示了如何调整`ddof`以得到相同的结果。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值