python参数估计置信区间_Python数据框的置信区间

该博客介绍了如何在Python中使用pandas数据框,通过groupby函数对不同类别计算'Force'列的平均值和95%置信区间。作者首先创建了一个示例数据框,然后通过计算标准差和样本数量来确定置信区间。最终,成功得到了每个类别力的平均值及其95%置信区间的计算结果。
摘要由CSDN通过智能技术生成

I am trying to calculate the mean and confidence interval(95%) of a column "Force" in a large dataset. I need the result by using the groupby function by grouping different "Classes".

When I calculate the mean and put it in the new dataframe, it gives me NaN values for all rows. I'm not sure if I'm going the correct way. Is there any easier way to do this?

This is the sample dataframe:

df=pd.DataFrame({ 'Class': ['A1','A1','A1','A2','A3','A3'],

'Force': [50,150,100,120,140,160] },

columns=['Class', 'Force'])

To calculate the confidence interval, the first step I did was to calculate the mean. This is what I used:

F1_Mean = df.groupby(['Class'])['Force'].mean()

This gave me NaN values for all rows.

解决方案import pandas as pd

import numpy as np

import math

df=pd.DataFrame({'Class': ['A1','A1','A1','A2','A3','A3'],

'Force': [50,150,100,120,140,160] },

columns=['Class', 'Force'])

print(df)

print('-'*30)

stats = df.groupby(['Class'])['Force'].agg(['mean', 'count', 'std'])

print(stats)

print('-'*30)

ci95_hi = []

ci95_lo = []

for i in stats.index:

m, c, s = stats.loc[i]

ci95_hi.append(m + 1.96*s/math.sqrt(c))

ci95_lo.append(m - 1.96*s/math.sqrt(c))

stats['ci95_hi'] = ci95_hi

stats['ci95_lo'] = ci95_lo

print(stats)

The output is

Class Force

0 A1 50

1 A1 150

2 A1 100

3 A2 120

4 A3 140

5 A3 160

------------------------------

mean count std

Class

A1 100 3 50.000000

A2 120 1 NaN

A3 150 2 14.142136

------------------------------

mean count std ci95_hi ci95_lo

Class

A1 100 3 50.000000 156.580326 43.419674

A2 120 1 NaN NaN NaN

A3 150 2 14.142136 169.600000 130.400000

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值