In Python with pandas, confidence interval for a mean for the sample data takes a few lines, shown below. It returns 2.61.
95% CI = Mean ± t(0.975, n − 1) × Standard deviation ÷ √n
Step by step
- Install the libraries (pip install pandas scipy) and save daily.csv next to your script.
- Run the script and compare the printed value with the expected result.
The code
from scipy import stats
import pandas as pd
df = pd.read_csv("daily.csv")
x = df["website_orders"]
margin = stats.t.ppf(0.975, len(x) - 1) * x.std() / len(x) ** 0.5
print(round(x.mean() - margin, 2), round(x.mean() + margin, 2))
Expected result on the sample data: 2.61.
What the result means
The figure here is the margin (the ± part) for average daily website orders. Add it to and subtract it from the mean to get the interval.
Notes for Python
- pandas methods such as .std(), .var() and .quantile() match Excel's sample versions (STDEV.S, VAR.S, PERCENTILE.INC). NumPy's np.std() and np.var() default to the population version instead.
- pandas skips NaN values in these calculations by default. Count how many rows were used if data might be missing.
Where confidence interval for a mean misleads
- It is about the average, not individual days. Most days fall outside the confidence interval for the mean, and that is expected.
- It assumes independent observations and a roughly normal sample mean, which 30 days usually give, but not with heavy trends or seasonality.
- CONFIDENCE.NORM uses the normal distribution; CONFIDENCE.T uses t, which is right for samples of this size.
The plain-language explanation is on the Confidence interval for a mean page.
The data
| day | website_orders |
|---|---|
| 1 | 24 |
| 2 | 27 |
| 3 | 22 |
| 4 | 30 |
| 5 | 28 |
| 6 | 25 |
| 7 | 31 |
| 8 | 29 |
| 9 | 26 |
| 10 | 33 |
| 11 | 30 |
| 12 | 28 |
| 13 | 35 |
| 14 | 32 |
| 15 | 29 |
| 16 | 34 |
| 17 | 61 |
| 18 | 31 |
| 19 | 36 |
| 20 | 33 |
| 21 | 30 |
| 22 | 37 |
| 23 | 35 |
| 24 | 32 |
| 25 | 38 |
| 26 | 36 |
| 27 | 34 |
| 28 | 40 |
| 29 | 37 |
| 30 | 39 |
Same method, other tools
Related methods
Learn more about Python
- Python and SQL for data analysis, side by side — 3 min read
- Data analysis methods and techniques, and when to use each — 3 min read
About the data on this page
The figures come from a small made-up dataset, printed above in full so you can check every number by hand. Download it as daily.csv. The results are computed from those rows when the page is built, and the Excel formulas, SQL and Python on these pages are run against the same rows before publishing, so the code and the answers agree.
To get these numbers from your own data without writing formulas, try AnalyzeIt: ask in plain words and it shows the working behind every figure.
Legal entity
Devansh Yadav
Moradabad, Uttar Pradesh
Governing law: Courts at Moradabad, Uttar Pradesh
Phone: +91 8433475698
Legal: legal@analyzeit.in