【问题标题】:95% confidence interval of single proportion in pandas timeseries using statsmodel使用 statsmodel 的 pandas 时间序列中单个比例的 95% 置信区间
【发布时间】:2021-08-16 01:14:18
【问题描述】:

我有一个时间序列数据框:

df = pd.DataFrame({'year':['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019'],
                       'total_count': [545,779,706,547,626,530,766,1235,1260,947], 
                       'rand_count':[96,184,148,154,160,149,124,274,322,301],
                       'rand_perc':[17.61,23.62,20.96,28.15,25.56,28.11,16.19,22.19,25.56,31.78]
                       })

这里;

df['rand_perc'] = (df['rand_count']/df['total_count'])*100

问题:

我想从df['total_count'] 计算df['rand_count'] 的单个比例的置信区间,在df 的每一行中,并绘制df['year'] 与df['rand_perc'] 与CI 作为误差条。我尝试使用 statsmodel 使用以下代码计算每一行的 CI:

import statsmodels.api as sm

df['CI'] =  df[['total_count', 'rand_count']].apply(lambda row: sm.stats.proportion_confint(count = 
df['rand_count'], nobs = df['total_count'], alpha = 0.05), axis = 1)

但是结果df['CI']每行所有CI的元组看起来很烦人;

0    ([0.14416430990026746, 0.2063732756491498, 0.1...
1    ([0.14416430990026746, 0.2063732756491498, 0.1...
2    ([0.14416430990026746, 0.2063732756491498, 0.1...
3    ([0.14416430990026746, 0.2063732756491498, 0.1...
4    ([0.14416430990026746, 0.2063732756491498, 0.1...
5    ([0.14416430990026746, 0.2063732756491498, 0.1...
6    ([0.14416430990026746, 0.2063732756491498, 0.1...
7    ([0.14416430990026746, 0.2063732756491498, 0.1...
8    ([0.14416430990026746, 0.2063732756491498, 0.1...
9    ([0.14416430990026746, 0.2063732756491498, 0.1...
Name: CI, dtype: object

想要的结果

df['CI'] 的每一行中两个元素的相应元组类似:

(0.144164, 0.206373)
(0.179606, 0.243846)
(0.221421, 0.242859)
...................

还有两个单独的列df[upper] 和df[lower] 分别表示df['CI'] 的上限和下限。

您的帮助将不胜感激。

非常感谢!

【问题讨论】:

  • 好像你用错了apply,把df换成row在apply下:df[['total_count', 'rand_count']].apply(lambda row: sm.stats.proportion_confint(count = row['rand_count'], nobs = row['total_count'], alpha = 0.05), axis = 1)
  • 这些函数的大多数方法都应该向量化,但返回的是一个 numpy 数组,用户需要将其放回具有正确索引的 DataFrame 中。
  • 谢谢@anky,真是个愚蠢的错误。我没有注意到......是的,它必须是那样的。再次感谢您的帮助!

标签: python pandas time-series statsmodels


【解决方案1】:

考虑分配多个列,这些列应该按索引排列,因为每个 docs:

当一个 pandas 对象返回时,索引从计数中获取。

df['lower_CI'], df['upper_CI'] =  sm.stats.proportion_confint(
                                      count = df['rand_count'],
                                      nobs = df['total_count'],
                                      alpha = 0.05
                                  )

【讨论】:

  • 非常感谢。没想到这么简单又好用的方法。它解决了我的问题。非常感谢!
猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2020-10-09
  • 1970-01-01
相关资源
最近更新 更多