Book contents

STATHARBOR ANALYTICS · INTRODUCTION TO STATISTICS · CHAPTER 24

Introduction to Python for Statistics

Python is a versatile programming language widely used in data science and statistics. This chapter provides a brief introduction to Python’s key data analysis libraries: NumPy, pandas and matplotlib. Readers already comfortable with Python may skip this chapter.

Python Basics

Install Python from https://www.python.org or use a distribution such as Anaconda. Python code can be executed in Jupyter notebooks, interactive consoles or scripts. Basic operations:

2 + 2
3 ** 2  # exponentiation
np.sqrt(9)

Variable assignment uses the equals sign. Lists, tuples and dictionaries are common data structures. Use square brackets for indexing: x[0] returns the first element of list x.

NumPy Arrays

NumPy provides efficient arrays for numerical computing. Create arrays with np.array() and perform element–wise operations:

import numpy as np
x = np.array([1, 2, 3, 4])
y = x * 2  # multiplies each element
mean_x = np.mean(x)

Multidimensional arrays (matrices) can be created by passing nested lists. Use np.dot() for matrix multiplication.

pandas DataFrames

pandas offers a DataFrame structure analogous to R data frames. Read data from CSV files using read_csv():

import pandas as pd
df = pd.read_csv("data.csv")
df.head()
df.describe()

Access columns via df[’column’] or attribute notation df.column. Use df.loc[row_index, column_name] to subset. pandas integrates well with NumPy for calculations and with matplotlib for plotting.

Plotting with matplotlib

matplotlib is a flexible plotting library. For a quick scatterplot and histogram:

import matplotlib.pyplot as plt

plt.scatter(df['height'], df['weight'])
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs Weight')
plt.show()

plt.hist(df['age'], bins=10)
plt.xlabel('Age')
plt.title('Histogram of Age')
plt.show()

For more sophisticated graphics, the seaborn library builds on matplotlib and integrates with pandas.

Simple Linear Regression in Python

Use statsmodels or scikit–learn to fit linear models. For example, using statsmodels:

import statsmodels.api as sm
X = sm.add_constant(df['height'])
model = sm.OLS(df['weight'], X).fit()
print(model.summary())

This prints the parameter estimates, standard errors and R2R^2.

Exercises

Practice

  1. Create a pandas DataFrame with columns for time and temperature. Compute the mean temperature and plot a time series line chart.

  2. Write a Python function that takes a list of numbers and returns the sample variance. Verify it matches np.var with ddof=1.

  3. Read a dataset from a URL using pandas (e.g., https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv). Compute summary statistics and visualise the relationship between tip and total bill.

  4. Use scikit–learn to fit a linear regression predicting mpg from horsepower in the Auto dataset. Compare the results with statsmodels.

References