pandas Python数据框架中的置信区间

cyej8jka  于 2023-06-20  发布在  Python
关注(0)|答案(4)|浏览(140)

我试图计算一个大型数据集中“力”列的平均值和置信区间(95%)。我需要的结果,通过使用分组不同的“类”的groupby功能。
当我计算平均值并将其放入新的dataframe中时,它为所有行提供NaN值。我不确定我走的路是否正确。有没有更简单的方法?
以下是示例数据框架:

df=pd.DataFrame({ 'Class': ['A1','A1','A1','A2','A3','A3'], 
                  'Force': [50,150,100,120,140,160] },
                   columns=['Class', 'Force'])

为了计算置信区间,我做的第一步是计算平均值。这就是我使用的:

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

这为所有行提供了NaN值。

soat7uwm

soat7uwm1#

2021年10月25日更新:@a-donda指出,95%应基于平均值的1.96 X标准差。

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)

输出为

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
jgwigjjp

jgwigjjp2#

你可以通过利用“sem”来简化@yoonghm解决方案,sem是平均值的标准误差。

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', 'sem'])
print(stats)
print('-'*30)

stats['ci95_hi'] = stats['mean'] + 1.96* stats['sem']
stats['ci95_lo'] = stats['mean'] - 1.96* stats['sem']
print(stats)
aiqt4smr

aiqt4smr3#

正如在评论中提到的,我不能复制你的错误,但你可以尝试检查你的数字存储为数字,而不是字符串。使用df.info()并确保相关列是float或int:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 2 columns):
Class    6 non-null object   # <--- non-number column
Force    6 non-null int64    # <--- number (int) column
dtypes: int64(1), object(1)
memory usage: 176.0+ bytes
mo49yndu

mo49yndu4#

我不想让你痛苦,但1.96 * sd公式是一个严重的过度简化,并导致在较小的样本中不好的结论。使用t分布代替:

import pandas as pd
import scipy.stats as stats

df=pd.DataFrame({'Class': ['A1','A1','A1','A2','A3','A3'],
                 'Force': [50,150,100,120,140,160] },
                 columns=['Class', 'Force'])
print(df)
grouped = df.groupby(['Class'])['Force'].agg(['mean', 'count', 'std'])

# Calculate the t-value for a 95% confidence interval
t_value = stats.t.ppf(0.975, grouped['count'] - 1)  # 0.975 corresponds to (1 - alpha/2)
# Calculate the margin of error
me = t_value * grouped['std'] / (grouped['count'] ** 0.5)
# Calculate the lower and upper bounds of the confidence interval   
grouped['ci_low'] = grouped['mean'] - me 
grouped['ci_high'] = grouped['mean'] + me 
print(grouped)

输出=

Class  Force
0    A1     50
1    A1    150
2    A1    100
3    A2    120
4    A3    140
5    A3    160
        mean  count        std     ci_low     ci_high
Class                                                
A1     100.0      3  50.000000 -24.206886  224.206886
A2     120.0      1        NaN        NaN         NaN
A3     150.0      2  14.142136  22.937953  277.062047

(已确认来自chatgpt 3.5的协助)

相关问题