Skip to content

Instantly share code, notes, and snippets.

@lundquist-ecology-lab
Last active January 14, 2023 19:28
Show Gist options
  • Save lundquist-ecology-lab/9a0b4d028a715c692ab2622b6274979b to your computer and use it in GitHub Desktop.
Save lundquist-ecology-lab/9a0b4d028a715c692ab2622b6274979b to your computer and use it in GitHub Desktop.
Standard error and 95% confidence intervals in Python
# Dealing with uncertainty in Python
import pandas as pd
import numpy as np
from scipy.stats import t
from palmerpenguins import load_penguins
penguins = load_penguins().dropna()
# Split the data frame into groups
groups = penguins.groupby('species')
# Calculate sample means, standard deviations, and standard errors for each group
means = groups['bill_length_mm'].mean()
std_devs = groups['bill_length_mm'].std()
sizes = groups['bill_length_mm'].size()
sems = groups['bill_length_mm'].sem()
# Calculate 95% CIs for each group
cis = {}
for group, mean, std_dev, size, sem in zip(means.index, means, std_devs, sizes, sems):
ci_1 = mean - (2 * sem)
ci_2 = mean + (2 * sem)
cis[group] = ci_1, ci_2
print(cis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment