w = 10 # assign the value 10 to the variable "w" x = 20 # assign the value 20 to the variable "x" y = 30
Py Notes for AGECON: Basics and Fundamentals
These notes introduce Python for agricultural economics, following the same steps as the R Notes for AGECON. The examples are intentionally basic: run each cell in order and compare the results with the outputs shown here.
1 Introduction to Python
Python is a free, open-source programming language that is widely used for data analysis, statistics, machine learning, and visualization. It is a general-purpose language, so the same skills you learn here will help you clean data, run regressions, build maps, and automate everyday tasks.
Python code is usually written in Jupyter notebooks: documents that mix text, code, and results, just like this one. Each block of code is called a cell, and you run cells one at a time to see their results right below them.
1.1 Installation
You have three easy options:
- Google Colab (no installation). Go to https://colab.research.google.com, sign in with a Google account, and create a new notebook. Most packages used here are already installed.
- Anaconda. Download it from https://www.anaconda.com/download. It installs Python, Jupyter, and the most common data packages in one step.
- VS Code. Install Python from https://www.python.org/downloads and the free editor from https://code.visualstudio.com, then add the Python and Jupyter extensions.
1.2 The Notebook Interface
A notebook has two kinds of cells:
- Code cells, where you write and run Python code.
- Text (Markdown) cells, where you write notes and explanations.
To run a cell, click inside it and press Shift + Enter, or click the play button next to the cell. The result appears below the cell. Cells share the same memory, so a variable created in one cell can be used in the next ones.
2 The Basics
2.1 Executing Code & Variable Creation
Below are a few lines of code. Type them into a code cell or copy and paste them from this document, then run the cell.
You have just assigned values to the variables w, x, and y. Unlike R, Python has a single assignment operator: =. Running the cell does not print anything; it only stores the values in memory.
Now run:
print(x, y) # print "x" and "y"
20 30
In a notebook, the value of the last line of a cell is also displayed automatically:
x
20
2.2 Python is Case Sensitive
Now run:
x = 5 # re-assign a new value to variable "x" a = 10 A = 20 print(x, a, A) # print "x", "a", and "A"
5 10 20
You have just seen that you can re-assign a new value to a variable. Be mindful of this as your scripts grow and include many variables.
Also, Python is case sensitive: a above equals 10 and A equals 20.
Putting # in front of a line prevents it from being executed. These comments are useful to leave yourself notes and reminders.
2.3 Missing Values
Python has two common ways to represent a missing value: None (plain Python) and np.nan ("not a number", from the NumPy package). In data analysis you will mostly see np.nan. Keep in mind that a missing value is not equal to zero.
import numpy as np # NumPy is the core package for numbers and arrays x = np.nan x
nan
Math operations with a missing value return a missing value:
print(x + 1) print(np.sum([1, x, 3]))
nan nan
However, NumPy has versions of its functions that ignore missing values, similar to na.rm = TRUE in R:
print(np.nansum([1, x, 3])) # sum, ignoring the missing value
4.0
2.4 Calculator and Math Functions
We will pick up the pace now. Comments are provided throughout to explain each function. Let us set x = 3 and y = 7.
x = 3 # re-assign a new value to variable "x" y = 7 print(x, y)
3 7
The lines below demonstrate basic mathematical operations. The math module, included with Python, provides functions such as square roots and logarithms.
import math print(x + y) # addition print(x - y) # subtraction print(x * y) # multiplication print(x / y) # division print(x * y * 1 - y) print(x * y * (1 - y)) # use parentheses to control the order of operations print(x ** 2) # exponent (R uses x^2) print(math.sqrt(x)) # square root print(round(x / y, 3)) # rounds x/y to 3 decimal places print(math.floor(x / y)) # largest integer less than or equal to x/y print(math.ceil(x / y)) # smallest integer greater than or equal to x/y print(abs(x - y)) # absolute value print(math.log(x)) # natural log (base e) print(math.log10(x)) # log base 10
10 -4 21 0.42857142857142855 14 -126 9 1.7320508075688772 0.429 0 1 4 1.0986122886681098 0.47712125471966244
Logical operators return True or False:
print(x == y) # is "x" equal to "y"? print(x != y) # is "x" not equal to "y"? print(x < 10) # is "x" less than 10? print(x <= 2) # is "x" less than or equal to 2? print(x < 20 and y >= 50) # is "x" less than 20 AND "y" at least 50? print(x < 20 or y >= 50) # is "x" less than 20 OR "y" at least 50? z = [1, 2, 3, 4] # a list of numbers print(z) print(x in z) # is "x" contained in "z"? print(x not in z) # is "x" not contained in "z"? print(5 in z) # is 5 contained in "z"?
False True True False False True [1, 2, 3, 4] True False False
If-else statements:
# returns x + y if x equals 100, otherwise returns None (missing) result1 = x + y if x == 100 else None # returns x + y if x is less than 100, otherwise returns None result2 = x + y if x < 100 else None print(result1, result2) # The same idea written as a full if-else block if x < 100: print("x is less than 100") else: print("x is 100 or more")
None 10 x is less than 100
Two more operators are very useful. Floor division // returns the whole-number part of a division, and the modulus % returns the remainder:
total_bushels = 1250 # bushels harvested truck_capacity = 400 # bushels per truck print(total_bushels // truck_capacity) # full truckloads: 3 print(total_bushels % truck_capacity) # bushels left over: 50
3 50
Economics Examples
Let us put these operations to work with a few everyday calculations in agricultural economics.
Unit conversion. Corn is traded in bushels, but international statistics use metric tons. One bushel of corn weighs 56 pounds, and one pound equals 0.45359237 kg:
bushels = 10000 kg_per_bushel = 56 * 0.45359237 # 25.4 kg per bushel of corn metric_tons = bushels * kg_per_bushel / 1000 print(round(metric_tons, 2), "metric tons")
254.01 metric tons
Revenue, cost, and profit for a 500-acre corn farm:
acres = 500 yield_bu_acre = 180 # bushels per acre price = 4.25 # dollars per bushel cost_per_acre = 690 # dollars per acre revenue = acres * yield_bu_acre * price total_cost = acres * cost_per_acre profit = revenue - total_cost margin = profit / revenue * 100 print("Revenue:", revenue) print("Total cost:", total_cost) print("Profit:", profit) print("Profit margin (%):", round(margin, 1))
Revenue: 382500.0 Total cost: 345000 Profit: 37500.0 Profit margin (%): 9.8
Break-even price: the price at which revenue just covers cost.
break_even_price = cost_per_acre / yield_bu_acre print("Break-even price ($/bu):", round(break_even_price, 2))
Break-even price ($/bu): 3.83
Percent change in the price of soybeans from one year to the next:
price_2023 = 13.20 price_2024 = 10.90 pct_change = (price_2024 - price_2023) / price_2023 * 100 print("Percent change:", round(pct_change, 1), "%")
Percent change: -17.4 %
Compound interest: the future value of $10,000 saved for 5 years at 4% interest per year, using $FV = PV(1 + r)^t$:
PV = 10000 # present value r = 0.04 # annual interest rate t = 5 # years FV = PV * (1 + r) ** t print("Future value:", round(FV, 2))
Future value: 12166.53
2.5 Understanding Variables in Python
Python uses several data types that you will encounter often. The type() function returns the type of any variable.
- Integer (
int): whole numbers.
a = 3 print(a) type(a)
3
<class 'int'>
- Float (
float): numbers with decimals. Converting a float to an integer withint()drops the decimal part.
b = 5.6 print(b, type(b)) b2 = int(5.6) # converts 5.6 to an integer print(b2, type(b2)) # notice the decimal part is dropped b3 = "6.7" # quotation marks make this text, not a number print(b3, type(b3))
5.6 <class 'float'> 5 <class 'int'> 6.7 <class 'str'>
- String (
str): text. You cannot do math with text, even if it looks like a number. The cell below shows the error you get when you try:
c = "WillieTheWildcat" print(c, type(c)) d = str(3) # "3" is now text print(d, type(d)) d + 1 # this produces an error
WillieTheWildcat <class 'str'> 3 <class 'str'>
TypeError: can only concatenate str (not "int") to str
To fix it, convert the text back to a number first:
int(d) + 1
4
- Boolean (
bool):TrueorFalse.
l_t = True l_f = False type(l_t)
<class 'bool'>
- Categorical: a variable with a fixed set of groups, similar to a factor in R. Categories come from the pandas package, which we use for data tables.
import pandas as pd # pandas is the main package for data tables US_state = pd.Categorical(["Kansas", "Iowa", "Nebraska", "Texas"]) US_state
['Kansas', 'Iowa', 'Nebraska', 'Texas'] Categories (4, str): ['Iowa', 'Kansas', 'Nebraska', 'Texas']
- Dates and times.
date_var = pd.Timestamp("2024-08-12") time_var = pd.Timestamp("2024-08-12 12:34:56") print(date_var.date(), type(date_var)) print(time_var) print(date_var.year, date_var.month, date_var.day) # extract parts of a date
2024-08-12 <class 'pandas.Timestamp'> 2024-08-12 12:34:56 2024 8 12
Converting Between Types
Data often arrives as text. For example, a price scraped from a website may look like "$4.25". To do math with it, remove the dollar sign and convert it to a float:
price_text = "$4.25" price = float(price_text.replace("$", "")) # remove "$", then convert to a number print(price * 2) quantity_text = "1,250" quantity = int(quantity_text.replace(",", "")) # remove the comma print(quantity + 1)
8.5 1251
Formatting Numbers with f-strings
An f-string (a string with f before the quotes) lets you place variables inside text and control how numbers are displayed:
revenue = 382500 rate = 0.0475 print(f"Revenue: ${revenue:,.2f}") # comma separators, 2 decimals print(f"Interest rate: {rate:.2%}") # shown as a percentage print(f"Revenue in millions: {revenue / 1e6:.2f} M")
Revenue: $382,500.00 Interest rate: 4.75% Revenue in millions: 0.38 M
Working with Dates
Dates are useful for questions like "how many days until harvest?" or "when does this loan mature?":
planting = pd.Timestamp("2024-04-25") harvest = pd.Timestamp("2024-10-05") season_length = harvest - planting print("Days from planting to harvest:", season_length.days) loan_start = pd.Timestamp("2024-03-01") maturity = loan_start + pd.DateOffset(months=18) # an 18-month operating loan print("Loan matures on:", maturity.date()) months = pd.date_range("2024-01-01", periods=6, freq="MS") # first day of each month print(months.strftime("%b %Y").tolist())
Days from planting to harvest: 163 Loan matures on: 2025-09-01 ['Jan 2024', 'Feb 2024', 'Mar 2024', 'Apr 2024', 'May 2024', 'Jun 2024']
2.6 Delete Objects from Memory
Use del to remove a variable. After deleting it, Python no longer knows the name.
x = 5 print(x) X = "My name is Willie" # assign a string to the variable "X" print(X) del x # remove "x" from memory # print(x) # this would now give an error: name 'x' is not defined
5 My name is Willie
2.7 Install and Import Packages
Packages add functions to Python. You install a package once, then import it in every notebook where you use it. To install packages, run the line below once (remove the # first). In Google Colab most of them are already installed.
# !pip install pandas numpy matplotlib seaborn statsmodels plotly openpyxl import numpy as np # arrays and math import pandas as pd # data tables (like data frames in R) import matplotlib.pyplot as plt # plots
Different Ways to Import
There are three common ways to import, and you will see all of them in other people's code:
import math # use as math.sqrt() import numpy as np # import with a short nickname (alias) from math import sqrt, exp # import only the functions you need print(math.sqrt(16), np.sqrt(16), sqrt(16)) print(exp(1)) # Euler's number e
4.0 4.0 4.0 2.718281828459045
3 Fundamentals
This section covers the building blocks you will use in almost every program: storing data in different structures, making decisions, repeating tasks, and writing your own functions. All examples use simple economics problems.
3.1 Data Structures: Lists, Tuples, Dictionaries, and Sets
Python has four built-in ways to store collections of values:
| Structure | Example | Ordered? | Can change? | Typical use |
|---|---|---|---|---|
| List | [4.25, 4.10, 4.40] |
Yes | Yes | a series of prices |
| Tuple | (39.19, -96.58) |
Yes | No | fixed values, such as coordinates |
| Dictionary | {"corn": 4.25} |
Yes | Yes | look up a value by its name |
| Set | {"Mexico", "Japan"} |
No | Yes | unique items, no duplicates |
Lists keep values in order and can be changed:
corn_prices = [4.25, 4.10, 4.40, 4.55] # weekly prices, $/bu corn_prices.append(4.60) # add a new week print(corn_prices) print("Weeks recorded:", len(corn_prices)) print("Average price:", round(sum(corn_prices) / len(corn_prices), 3))
[4.25, 4.1, 4.4, 4.55, 4.6] Weeks recorded: 5 Average price: 4.38
Tuples are like lists but cannot be changed after they are created, which protects values that should stay fixed:
manhattan_ks = (39.19, -96.58) # latitude, longitude lat, lon = manhattan_ks # "unpack" a tuple into two variables print("Latitude:", lat, " Longitude:", lon)
Latitude: 39.19 Longitude: -96.58
Dictionaries store key: value pairs, so you can look up a value by name:
prices = {"corn": 4.25, "soybeans": 10.90, "wheat": 5.60} # $/bu print(prices["soybeans"]) # look up a value by its key prices["sorghum"] = 4.05 # add a new commodity prices["corn"] = 4.30 # update an existing one print(prices) print(list(prices.keys()))
10.9
{'corn': 4.3, 'soybeans': 10.9, 'wheat': 5.6, 'sorghum': 4.05}
['corn', 'soybeans', 'wheat', 'sorghum']
Sets keep only unique values, which makes it easy to compare groups. For example, the destination markets of two exporters:
exporter_a = {"Mexico", "Japan", "China", "Colombia"} exporter_b = {"Japan", "China", "Egypt", "Mexico", "Japan"} # "Japan" twice print(exporter_b) # duplicates are removed print(exporter_a & exporter_b) # markets both export to (intersection) print(exporter_a | exporter_b) # all markets (union) print(exporter_a - exporter_b) # markets only exporter A serves
{'Japan', 'Mexico', 'China', 'Egypt'}
{'Japan', 'Mexico', 'China'}
{'Mexico', 'Colombia', 'Japan', 'China', 'Egypt'}
{'Colombia'}
3.2 If Statements
if, elif (else if), and else let a program make decisions. Python uses indentation (four spaces) to know which lines belong to each branch.
Classify a farm's financial result:
profit = -12500 if profit > 0: print("The farm made a profit.") elif profit == 0: print("The farm broke even.") else: print("The farm had a loss of", abs(profit), "dollars.")
The farm had a loss of 12500 dollars.
A price floor: if the market price falls below a support price, a payment covers the difference. (The support price below is hypothetical.)
support_price = 3.70 # hypothetical support price, $/bu market_price = 3.45 bushels = 50000 if market_price < support_price: payment = (support_price - market_price) * bushels print(f"Payment: ${payment:,.2f}") else: print("No payment: the market price is above the support price.")
Payment: $12,500.00
Several conditions can be combined. Here, a loan is approved only if two financial ratios meet hypothetical thresholds:
debt_to_asset = 0.35 current_ratio = 1.8 # current assets / current liabilities if debt_to_asset < 0.40 and current_ratio > 1.5: print("Loan approved") else: print("Loan needs further review")
Loan approved
3.3 For Loops
A for loop repeats the same steps for each item in a collection.
Revenue for each crop on a farm:
crops = {"corn": (300, 180, 4.25), # (acres, bu/acre, $/bu) "soybeans": (200, 55, 10.90), "wheat": (100, 50, 5.60)} total = 0 for crop, (acres, yld, price) in crops.items(): revenue = acres * yld * price total += revenue # same as total = total + revenue print(f"{crop:<9} revenue: ${revenue:>11,.2f}") print(f"{'Total':<9} revenue: ${total:>11,.2f}")
corn revenue: $ 229,500.00 soybeans revenue: $ 119,900.00 wheat revenue: $ 28,000.00 Total revenue: $ 377,400.00
Growth of an investment year by year, using range() to count:
balance = 10000 rate = 0.05 for year in range(1, 6): # years 1 to 5 balance = balance * (1 + rate) print(f"Year {year}: ${balance:,.2f}")
Year 1: $10,500.00 Year 2: $11,025.00 Year 3: $11,576.25 Year 4: $12,155.06 Year 5: $12,762.82
3.4 While Loops
A while loop repeats as long as a condition is true. It is useful when you do not know in advance how many repetitions you need.
How many years does it take to double an investment at 6% per year?
balance = 1000 years = 0 while balance < 2000: balance = balance * 1.06 years += 1 print("Years to double:", years, f"(final balance ${balance:,.2f})")
Years to double: 12 (final balance $2,012.20)
Paying off a $20,000 equipment loan with $5,000 payments per year at 7% interest:
debt = 20000 payment = 5000 rate = 0.07 year = 0 while debt > 0: year += 1 debt = debt * (1 + rate) - payment # interest is added, then the payment is made print(f"Year {year}: remaining debt ${max(debt, 0):,.2f}")
Year 1: remaining debt $16,400.00 Year 2: remaining debt $12,548.00 Year 3: remaining debt $8,426.36 Year 4: remaining debt $4,016.21 Year 5: remaining debt $0.00
Always make sure the condition eventually becomes false; otherwise the loop runs forever. If that happens, stop the cell with the stop button.
3.5 List Comprehensions
A list comprehension builds a new list in one line. It is a compact version of a for loop.
Convert nominal prices into real prices (adjusted for inflation) with a price index:
nominal = [3.50, 3.70, 4.10, 5.90, 6.50] # $/bu cpi = [100, 102, 105, 110, 118] # price index (base year = 100) real = [round(p / i * 100, 2) for p, i in zip(nominal, cpi)] print(real)
[3.5, 3.63, 3.9, 5.36, 5.51]
Add a condition to keep only some items. Here, keep the crops whose profit per acre is positive:
profit_per_acre = {"corn": 75, "soybeans": 120, "wheat": -20, "sorghum": 10} profitable = [crop for crop, p in profit_per_acre.items() if p > 0] print(profitable)
['corn', 'soybeans', 'sorghum']
3.6 Functions
A function packages steps you want to reuse. You define it once with def and then call it as many times as you need. The text in triple quotes, called a docstring, explains what the function does.
Net present value (NPV) of a stream of cash flows, $NPV = \sum_t \frac{CF_t}{(1+r)^t}$:
def npv(rate, cash_flows): """Net present value. cash_flows[0] happens today (year 0).""" return sum(cf / (1 + rate) ** t for t, cf in enumerate(cash_flows)) # Buy a $50,000 grain bin that saves $9,000 per year for 8 years flows = [-50000] + [9000] * 8 print(f"NPV at 6%: {npv(0.06, flows):,.2f} dollars") print(f"NPV at 10%: {npv(0.10, flows):,.2f} dollars")
NPV at 6%: 5,888.14 dollars NPV at 10%: -1,985.66 dollars
A positive NPV means the investment earns more than the interest rate used to discount it. Functions can also have default values for some inputs. Below, the price elasticity of demand uses the midpoint formula:
def elasticity(q1, q2, p1, p2, method="midpoint"): """Price elasticity of demand between two points.""" if method == "midpoint": pct_q = (q2 - q1) / ((q1 + q2) / 2) pct_p = (p2 - p1) / ((p1 + p2) / 2) else: pct_q = (q2 - q1) / q1 pct_p = (p2 - p1) / p1 return pct_q / pct_p e = elasticity(q1=100, q2=70, p1=2.00, p2=2.50) print("Elasticity:", round(e, 2)) if abs(e) > 1: print("Demand is elastic: quantity responds more than price.") elif abs(e) < 1: print("Demand is inelastic: quantity responds less than price.") else: print("Demand is unit elastic.")
Elasticity: -1.59 Demand is elastic: quantity responds more than price.
Annual payment on a loan, using $A = P\,\frac{r}{1-(1+r)^{-n}}$:
def loan_payment(principal, rate, years): """Equal annual payment that repays a loan.""" return principal * rate / (1 - (1 + rate) ** -years) print(f"Tractor loan: ${loan_payment(150000, 0.065, 7):,.2f} per year")
Tractor loan: $27,349.71 per year
3.7 Lambda Functions
A lambda is a small, one-line function without a name. Lambdas are handy when a function is needed only once, for example to tell Python how to sort.
Sort crops by revenue per acre:
crops = [("corn", 180 * 4.25), ("soybeans", 55 * 10.90), ("wheat", 50 * 5.60)] by_revenue = sorted(crops, key=lambda c: c[1], reverse=True) # sort by the second item print(by_revenue)
[('corn', 765.0), ('soybeans', 599.5), ('wheat', 280.0)]
Lambdas also work well with pandas. Here we classify farms by size:
farms_df = pd.DataFrame({"farm": ["A", "B", "C", "D"], "acres": [120, 850, 2400, 430]}) farms_df["size"] = farms_df["acres"].apply(lambda a: "small" if a < 500 else ("medium" if a < 2000 else "large")) farms_df
| farm | acres | size | |
|---|---|---|---|
| 0 | A | 120 | small |
| 1 | B | 850 | medium |
| 2 | C | 2400 | large |
| 3 | D | 430 | small |
3.8 Error Handling
Errors happen, for example when data contain a zero or a typo. try and except let your program handle an error gracefully instead of stopping.
Average cost per unit when production can be zero:
def average_cost(total_cost, quantity): try: return total_cost / quantity except ZeroDivisionError: print("Quantity is zero: average cost is undefined.") return None print(average_cost(5000, 250)) print(average_cost(5000, 0))
20.0 Quantity is zero: average cost is undefined. None
Converting messy price data, where some entries are not numbers:
raw_prices = ["4.25", "4.10", "n/a", "4.40", ""] clean = [] for p in raw_prices: try: clean.append(float(p)) except ValueError: clean.append(np.nan) # mark it as missing instead of stopping print(clean) print("Average of valid prices:", round(np.nanmean(clean), 3))
[4.25, 4.1, nan, 4.4, nan] Average of valid prices: 4.25
3.9 User Inputs
The input() function asks the user to type a value. Everything typed comes in as text, so convert it with float() or int(). Run the cell below yourself and answer the questions.
price = float(input("Expected price ($/bu): ")) yld = float(input("Expected yield (bu/acre): ")) cost = float(input("Cost per acre ($): ")) profit = price * yld - cost print(f"Expected profit: ${profit:,.2f} per acre")
3.10 Objects and Classes
A class is a blueprint that bundles data (attributes) and functions (methods) together. Each object created from the class has its own data. This is how packages such as pandas are built.
class Farm: """A simple farm business with one crop.""" def __init__(self, name, acres, yield_bu, price, cost_per_acre): self.name = name self.acres = acres self.yield_bu = yield_bu self.price = price self.cost_per_acre = cost_per_acre def revenue(self): return self.acres * self.yield_bu * self.price def cost(self): return self.acres * self.cost_per_acre def profit(self): return self.revenue() - self.cost() def break_even_price(self): return self.cost_per_acre / self.yield_bu farm1 = Farm("Prairie View", acres=500, yield_bu=180, price=4.25, cost_per_acre=690) farm2 = Farm("Blue River", acres=320, yield_bu=150, price=4.25, cost_per_acre=700) for f in [farm1, farm2]: print(f"{f.name}: profit {f.profit():,.0f} dollars, break-even price ${f.break_even_price():.2f}/bu")
Prairie View: profit 37,500 dollars, break-even price $3.83/bu Blue River: profit -20,000 dollars, break-even price $4.67/bu
Because each farm is an object, you can change one attribute and recalculate:
farm2.price = 4.80 # a better marketing price print(f"{farm2.name} profit at $4.80: {farm2.profit():,.0f} dollars")
Blue River profit at $4.80: 6,400 dollars
3.11 Saving Data and Objects
pickle saves almost any Python object (a dictionary of results, a list, a fitted model) to a file and loads it back later exactly as it was.
import pickle results = {"npv_grain_bin": npv(0.06, flows), "loan_payment": loan_payment(150000, 0.065, 7)} with open("results.pkl", "wb") as f: # "wb" = write binary pickle.dump(results, f) with open("results.pkl", "rb") as f: # "rb" = read binary loaded = pickle.load(f) print(loaded)
{'npv_grain_bin': 5888.144298725972, 'loan_payment': 27349.705396633257}
For DataFrames, pandas has its own shortcut:
farms_df.to_pickle("farms.pkl") pd.read_pickle("farms.pkl")
| farm | acres | size | |
|---|---|---|---|
| 0 | A | 120 | small |
| 1 | B | 850 | medium |
| 2 | C | 2400 | large |
| 3 | D | 430 | small |
3.12 SQLite Databases
Large datasets often live in databases, which you query with SQL. Python includes sqlite3, a small database that needs no installation. Let us store monthly commodity prices and query them. The prices are simulated for practice.
import sqlite3 rng = np.random.default_rng(7) months = pd.date_range("2024-01-01", periods=12, freq="MS").strftime("%Y-%m") price_table = pd.DataFrame({ "month": list(months) * 2, "commodity": ["corn"] * 12 + ["soybeans"] * 12, "price": np.r_[rng.normal(4.4, 0.2, 12), rng.normal(11.5, 0.5, 12)].round(2), }) conn = sqlite3.connect("prices.db") # creates the file if needed price_table.to_sql("prices", conn, if_exists="replace", index=False) query = """ SELECT commodity, ROUND(AVG(price), 2) AS avg_price, MIN(price) AS min_price, MAX(price) AS max_price FROM prices GROUP BY commodity """ summary = pd.read_sql(query, conn) conn.close() summary
| commodity | avg_price | min_price | max_price | |
|---|---|---|---|---|
| 0 | corn | 4.38 | 4.20 | 4.67 |
| 1 | soybeans | 11.16 | 10.55 | 11.85 |
3.13 Interactive Widgets
In Jupyter and Google Colab, the ipywidgets package adds sliders and buttons, so you can see how results change when an input changes. Move the sliders to see how price and yield affect profit per acre. Run it yourself; widgets do not work on this web page.
# !pip install ipywidgets # already installed in Google Colab from ipywidgets import interact @interact(price=(3.0, 7.0, 0.1), yield_bu=(100, 250, 5)) def profit_per_acre(price=4.25, yield_bu=180): cost = 690 profit = price * yield_bu - cost print(f"Profit: ${profit:,.2f} per acre")
4 Arrays, Matrices, and DataFrames
4.1 Creating Arrays
In Python, a sequence of values can be stored in a list, but for numbers we usually use a NumPy array, which works like a vector in R.
v1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # creates a numeric array print(v1, type(v1)) v2 = np.arange(1, 11) # another way: numbers from 1 up to (but not including) 11 print(v2) print(v2[2]) # returns the THIRD element: Python counts from 0! v1b = np.repeat(1, 5) # repeats 1 five times print(v1b) rng = np.random.default_rng(10110) # random number generator with a seed for reproducibility v3 = rng.choice(np.arange(1, 21), size=5, replace=False) # 5 random numbers from 1 to 20 print(v3) random = rng.normal(loc=0, scale=1, size=5) # 5 draws from a standard normal distribution print(random) char = ["Kansas", "Missouri", "Oklahoma"] # a list of strings print(char, len(char)) # len() returns the number of elements
[ 1 2 3 4 5 6 7 8 9 10] <class 'numpy.ndarray'> [ 1 2 3 4 5 6 7 8 9 10] 3 [1 1 1 1 1] [ 4 3 20 16 12] [0.73598249 1.35000375 1.03122517 0.68942014 0.45764849] ['Kansas', 'Missouri', 'Oklahoma'] 3
4.2 Extracting Elements
The most important difference from R: Python starts counting at 0. The first element is [0], the second is [1], and so on. A range like [2:5] includes position 2 but stops before position 5.
vec = np.round(rng.normal(loc=50, scale=8, size=10)) # 10 random numbers, rounded print(vec) # all elements print(vec[2]) # the third element print(vec[[2, 3]]) # the third and fourth elements print(vec[2:5]) # the third through the fifth elements print(vec[1:]) # all but the first element print(np.delete(vec, [0, 1])) # all but the first and second elements print(vec[3:]) # all but the first three elements
[50. 49. 45. 54. 49. 47. 54. 53. 57. 58.] 45.0 [45. 54.] [45. 54. 49.] [49. 45. 54. 49. 47. 54. 53. 57. 58.] [45. 54. 49. 47. 54. 53. 57. 58.] [54. 49. 47. 54. 53. 57. 58.]
Negative positions count from the end, which is handy for the most recent observations:
monthly_prices = np.array([4.10, 4.25, 4.18, 4.40, 4.52, 4.47]) print(monthly_prices[-1]) # the last (most recent) price print(monthly_prices[-3:]) # the last three months print(monthly_prices[::2]) # every other month
4.47 [4.4 4.52 4.47] [4.1 4.18 4.52]
Strings can be sliced the same way. For example, to extract the year and month from a date written as text:
date_text = "2024-08-12" print(date_text[:4]) # year print(date_text[5:7]) # month
2024 08
4.3 Numeric Operations on Arrays
Let us create some arrays.
a = np.arange(1, 6) b = np.arange(6, 11) print(a, b)
[1 2 3 4 5] [ 6 7 8 9 10]
Operations on arrays happen element by element:
print(a + 1) # add 1 to each element of a print(b * 2) # multiply each element of b by 2 print(a + b) # elementwise addition print(a - b) # elementwise subtraction print(a * b) # elementwise multiplication print(a / b) # elementwise division
[2 3 4 5 6] [12 14 16 18 20] [ 7 9 11 13 15] [-5 -5 -5 -5 -5] [ 6 14 24 36 50] [0.16666667 0.28571429 0.375 0.44444444 0.5 ]
4.4 Summary Statistics for Arrays
x = rng.normal(size=10) print(x) print("sum:", x.sum()) print("mean:", x.mean()) print("median:", np.median(x)) print("variance:", x.var(ddof=1)) # ddof=1 gives the sample variance, like R's var() print("std. dev.:", x.std(ddof=1)) print("min:", x.min(), "max:", x.max()) print(np.sort(x)) # sort from lowest to highest print(np.sort(x)[::-1]) # sort from highest to lowest
[-0.63371113 -1.04243101 -1.73456133 1.15270304 0.53543853 -0.99916249 1.19879733 0.01596693 -0.09718134 0.71579696] sum: -0.8883445224410862 mean: -0.08883445224410862 median: -0.04060720500842985 variance: 0.9989959416418588 std. dev.: 0.9994978447409774 min: -1.7345613317372117 max: 1.1987973275853736 [-1.73456133 -1.04243101 -0.99916249 -0.63371113 -0.09718134 0.01596693 0.53543853 0.71579696 1.15270304 1.19879733] [ 1.19879733 1.15270304 0.71579696 0.53543853 0.01596693 -0.09718134 -0.63371113 -0.99916249 -1.04243101 -1.73456133]
Let us create another array.
y = np.concatenate([[1, 1], np.arange(4, 21, 2)]) print(y) print(np.unique(y)) # unique elements of "y" print(len(np.unique(y))) # number of unique elements pd.Series(y).value_counts().sort_index() # frequency table of "y"
[ 1 1 4 6 8 10 12 14 16 18 20] [ 1 4 6 8 10 12 14 16 18 20] 10
1 2 4 1 6 1 8 1 10 1 12 1 14 1 16 1 18 1 20 1 Name: count, dtype: int64
Now an array with a missing value:
z = np.array([1, 2, 3, 4, np.nan, 6]) print(z) print(np.sum(z)) # returns nan because of the missing value print(np.nansum(z)) # ignores the missing value print(np.isnan(z)) # True where values are missing print(np.isnan(z).sum()) # number of missing values
[ 1. 2. 3. 4. nan 6.] nan 16.0 [False False False False True False] 1
Economics Example: Price Risk
NumPy makes it easy to describe price risk. Below we simulate 1,000 possible harvest prices and summarize them. The cumulative sum np.cumsum() also gives running totals, such as cumulative sales.
rng = np.random.default_rng(2025) harvest_prices = rng.normal(loc=4.30, scale=0.45, size=1000) # simulated $/bu print("Mean price:", harvest_prices.mean().round(2)) print("5th and 95th percentiles:", np.percentile(harvest_prices, [5, 95]).round(2)) print("Probability price < $3.80:", (harvest_prices < 3.80).mean()) weekly_sales = np.array([1200, 800, 1500, 1000, 900]) # bushels sold each week print("Cumulative sales:", np.cumsum(weekly_sales))
Mean price: 4.3 5th and 95th percentiles: [3.56 5.03] Probability price < $3.80: 0.131 Cumulative sales: [1200 2000 3500 4500 5400]
4.5 Creating Matrices
A matrix is a two-dimensional NumPy array.
a = np.arange(1, 11).reshape(2, 5) # 2 x 5 matrix, filled row by row print(a) b = np.arange(1, 11).reshape(2, 5, order="F") # filled column by column print(b) print(b.T) # transpose of "b" i = np.eye(5) # 5 x 5 identity matrix print(i)
[[ 1 2 3 4 5] [ 6 7 8 9 10]] [[ 1 3 5 7 9] [ 2 4 6 8 10]] [[ 1 2] [ 3 4] [ 5 6] [ 7 8] [ 9 10]] [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]]
Now let us combine arrays into matrices.
c = np.arange(1, 6) d = np.arange(6, 11) e = np.column_stack([c, d]) # bind as columns print(e) f = np.vstack([c, d]) # bind as rows print(f)
[[ 1 6] [ 2 7] [ 3 8] [ 4 9] [ 5 10]] [[ 1 2 3 4 5] [ 6 7 8 9 10]]
4.6 Extracting Matrix Elements
Inside the square brackets, the first number is the row and the second is the column. A colon : means "all".
print(e.shape) # dimensions (rows, columns) print(f.shape) print(e[0, :]) # first row print(e[:, 0]) # first column print(e[1, 1]) # a single element: 2nd row, 2nd column g = np.arange(1, 26).reshape(5, 5, order="F") # a 5 x 5 matrix print(g) g2 = g[2:, 2:] # drop the 1st and 2nd rows and columns print(g2) # now a 3 x 3 print(np.diag(g2)) # diagonal elements
(5, 2) (2, 5) [1 6] [1 2 3 4 5] 7 [[ 1 6 11 16 21] [ 2 7 12 17 22] [ 3 8 13 18 23] [ 4 9 14 19 24] [ 5 10 15 20 25]] [[13 18 23] [14 19 24] [15 20 25]] [13 19 25]
4.7 Numeric Operations on Matrices
h = np.arange(1, 26).reshape(5, 5) i = np.arange(26, 51).reshape(5, 5) print(h + i) # elementwise addition (same dimensions required) print(h - i) # elementwise subtraction print(h * i) # elementwise multiplication print(2 * h) # scalar multiplication print(h @ i) # matrix multiplication (R uses %*%)
[[27 29 31 33 35] [37 39 41 43 45] [47 49 51 53 55] [57 59 61 63 65] [67 69 71 73 75]] [[-25 -25 -25 -25 -25] [-25 -25 -25 -25 -25] [-25 -25 -25 -25 -25] [-25 -25 -25 -25 -25] [-25 -25 -25 -25 -25]] [[ 26 54 84 116 150] [ 186 224 264 306 350] [ 396 444 494 546 600] [ 656 714 774 836 900] [ 966 1034 1104 1176 1250]] [[ 2 4 6 8 10] [12 14 16 18 20] [22 24 26 28 30] [32 34 36 38 40] [42 44 46 48 50]] [[ 590 605 620 635 650] [1490 1530 1570 1610 1650] [2390 2455 2520 2585 2650] [3290 3380 3470 3560 3650] [4190 4305 4420 4535 4650]]
4.8 Combine Arrays and Modify Elements
v1 = np.arange(1, 11) v2 = np.arange(1, 11) v3 = rng.choice(np.arange(1, 21), size=10, replace=False) df1 = pd.DataFrame({"v1": v1, "v2": v2, "v3": v3}) # a data table from arrays print(df1.head()) df5 = np.vstack([v1, v2, v3]) # a matrix with 3 rows df5[1, 2] = 50 # replace the value in the 2nd row, 3rd column print(df5)
v1 v2 v3 0 1 1 3 1 2 2 19 2 3 3 9 3 4 4 20 4 5 5 14 [[ 1 2 3 4 5 6 7 8 9 10] [ 1 2 50 4 5 6 7 8 9 10] [ 3 19 9 20 14 11 7 16 8 12]]
4.9 Lists Can Hold Different Things
A Python list can contain objects of different types and sizes, similar to a list in R.
lst = [v1, df1.shape, 45, "text"] for item in lst: print(type(item).__name__, ":", item)
ndarray : [ 1 2 3 4 5 6 7 8 9 10] tuple : (10, 3) int : 45 str : text
4.10 A List of Strings
Unlike an R vector, a Python list keeps the type of each element, so numbers and text can sit side by side.
str_vec = ["R", "Python", "Stata", "SAS"] print(str_vec) str_vec1 = ["R", "Python", "Stata", "SAS", 11, "12", str(13)] print([type(s).__name__ for s in str_vec1]) # the type of each element
['R', 'Python', 'Stata', 'SAS'] ['str', 'str', 'str', 'str', 'int', 'str', 'str']
4.11 System of Equations
Now let us solve the following system of equations:
$$x_1 + 2x_2 = 10$$ $$3x_1 + 4x_2 = 25$$
# In matrix form this is A * X = B A = np.array([[1, 2], [3, 4]]) B = np.array([10, 25]) X = np.linalg.solve(A, B) X
array([5. , 2.5])
So $x_1 = 5$ and $x_2 = 2.5$.
4.12 Creating DataFrames
A DataFrame is a table where each column can have a different data type, just like a data frame in R. DataFrames come from the pandas package.
people = pd.DataFrame({ "Name": ["Bob", "John", "Susan", "Mary"], "Age": [22, 35, 40, 28], "Gender": pd.Categorical(["M", "M", "F", "F"]), }) people
| Name | Age | Gender | |
|---|---|---|---|
| 0 | Bob | 22 | M |
| 1 | John | 35 | M |
| 2 | Susan | 40 | F |
| 3 | Mary | 28 | F |
print(type(people)) print(people.shape) # 4 rows (observations), 3 columns (variables) people.dtypes # the data type of each column
<class 'pandas.DataFrame'> (4, 3)
Name str Age int64 Gender category dtype: object
4.13 Extracting DataFrame Elements
print(people.iloc[0]) # first row (by position) print(people.iloc[:, 0]) # first column (by position) print(people["Name"]) # a column by name print(people.Name) # another way print(list(people.index)) # row labels (0, 1, 2, ... by default) print(list(people.columns)) # column names
Name Bob Age 22 Gender M Name: 0, dtype: object 0 Bob 1 John 2 Susan 3 Mary Name: Name, dtype: str 0 Bob 1 John 2 Susan 3 Mary Name: Name, dtype: str 0 Bob 1 John 2 Susan 3 Mary Name: Name, dtype: str [0, 1, 2, 3] ['Name', 'Age', 'Gender']
4.14 Useful DataFrame Functions
people.describe(include="all") # summary of every column
| Name | Age | Gender | |
|---|---|---|---|
| count | 4 | 4.000000 | 4 |
| unique | 4 | NaN | 2 |
| top | Bob | NaN | F |
| freq | 1 | NaN | 2 |
| mean | NaN | 31.250000 | NaN |
| std | NaN | 7.889867 | NaN |
| min | NaN | 22.000000 | NaN |
| 25% | NaN | 26.500000 | NaN |
| 50% | NaN | 31.500000 | NaN |
| 75% | NaN | 36.250000 | NaN |
| max | NaN | 40.000000 | NaN |
people2 = people.iloc[1:].copy() # a new table without the first row people2["GenderDummy"] = np.where(people2["Gender"] == "M", 1, 0) # dummy variable people2
| Name | Age | Gender | GenderDummy | |
|---|---|---|---|---|
| 1 | John | 35 | M | 1 |
| 2 | Susan | 40 | F | 0 |
| 3 | Mary | 28 | F | 0 |
5 Working Directory, Importing, and Exporting
5.1 Working Directory
The working directory is the folder where Python looks for files to import and where it saves files you export.
import os os.getcwd() # returns the path of the working directory
'/content'
To change it, use os.chdir() with your own folder. Forward slashes / work on both Windows and Mac.
os.chdir("C:/Users/Walter/Documents/Python_session") # Windows example # os.chdir("/Users/your-username/Documents/Python_session") # Mac example
Navigating Folders
The os module also lets you list files, create folders, and build file paths that work on any computer. glob finds files that match a pattern.
import glob os.makedirs("data/raw", exist_ok=True) # create folders (no error if they exist) path = os.path.join("data", "raw", "prices.csv") # builds "data/raw/prices.csv" print(path) pd.DataFrame({"price": [4.25, 4.10]}).to_csv(path, index=False) print(os.listdir("data/raw")) # files in a folder print(glob.glob("data/**/*.csv", recursive=True)) # all CSV files under "data"
data/raw/prices.csv ['prices.csv'] ['data/raw/prices.csv']
5.2 Importing
In class, you will import the demographics.csv file that was provided to you. Make sure it is in your working directory, then run:
demographics = pd.read_csv("demographics.csv") demographics.iloc[:10, :10] # first 10 rows and first 10 columns
So that this notebook runs anywhere, we will practice with a small simulated household dataset that has the same kind of variables. The numbers are randomly generated for practice only.
rng = np.random.default_rng(2024) n = 10 demographics = pd.DataFrame({ "HHNUM": np.arange(1001, 1001 + n), "NONMETRO": rng.integers(0, 2, n), "REGION": rng.integers(1, 5, n), "RURAL": rng.integers(0, 2, n), "HHSIZE": rng.integers(1, 7, n), "INCHHAVG_R": rng.normal(65000, 20000, n).round(0), "PCTPOVGUIDEHH_R": rng.normal(300, 100, n).round(1), "POVTHRESHOLDHH": rng.normal(26000, 6000, n).round(0), "SELFEMPHH": rng.integers(0, 2, n), "EXPRENTMRTG_R": rng.normal(1200, 300, n).round(0), }) demographics.to_csv("demographics_example.csv", index=False) # save it to practice importing demographics = pd.read_csv("demographics_example.csv") # import the CSV file demographics.head()
| HHNUM | NONMETRO | REGION | RURAL | HHSIZE | INCHHAVG_R | PCTPOVGUIDEHH_R | POVTHRESHOLDHH | SELFEMPHH | EXPRENTMRTG_R | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1001 | 0 | 1 | 0 | 2 | 83061.0 | 305.7 | 23674.0 | 1 | 1413.0 |
| 1 | 1002 | 1 | 1 | 1 | 3 | 35388.0 | 342.5 | 17668.0 | 0 | 940.0 |
| 2 | 1003 | 0 | 4 | 1 | 1 | 54318.0 | 322.5 | 13411.0 | 1 | 1184.0 |
| 3 | 1004 | 0 | 1 | 1 | 6 | 68276.0 | 465.8 | 29806.0 | 0 | 1381.0 |
| 4 | 1005 | 0 | 1 | 1 | 4 | 51631.0 | 233.6 | 19008.0 | 1 | 1136.0 |
6 Data Wrangling
6.1 Data Exploration
Before exporting, let us explore the data.
print(demographics.shape) # dimensions (rows, columns) print(list(demographics.columns)) # variable names print(type(demographics)) demographics.dtypes # data type of each variable
(10, 10) ['HHNUM', 'NONMETRO', 'REGION', 'RURAL', 'HHSIZE', 'INCHHAVG_R', 'PCTPOVGUIDEHH_R', 'POVTHRESHOLDHH', 'SELFEMPHH', 'EXPRENTMRTG_R'] <class 'pandas.DataFrame'>
HHNUM int64 NONMETRO int64 REGION int64 RURAL int64 HHSIZE int64 INCHHAVG_R float64 PCTPOVGUIDEHH_R float64 POVTHRESHOLDHH float64 SELFEMPHH int64 EXPRENTMRTG_R float64 dtype: object
6.2 Data Manipulation
Say we are only interested in a subset of the data. Let us keep the first 10 rows and 10 columns, and rename the variables to something more readable.
household = demographics.iloc[:10, :10].copy() household.columns = ["hhnum", "nonmetro", "Region", "Rural", "Household_size", "Income_hhavg_r", "pctpovguidehh_r", "povthresholh_hh", "Selfemployment", "exprentmrtg_r"] household.head(10)
| hhnum | nonmetro | Region | Rural | Household_size | Income_hhavg_r | pctpovguidehh_r | povthresholh_hh | Selfemployment | exprentmrtg_r | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1001 | 0 | 1 | 0 | 2 | 83061.0 | 305.7 | 23674.0 | 1 | 1413.0 |
| 1 | 1002 | 1 | 1 | 1 | 3 | 35388.0 | 342.5 | 17668.0 | 0 | 940.0 |
| 2 | 1003 | 0 | 4 | 1 | 1 | 54318.0 | 322.5 | 13411.0 | 1 | 1184.0 |
| 3 | 1004 | 0 | 1 | 1 | 6 | 68276.0 | 465.8 | 29806.0 | 0 | 1381.0 |
| 4 | 1005 | 0 | 1 | 1 | 4 | 51631.0 | 233.6 | 19008.0 | 1 | 1136.0 |
| 5 | 1006 | 0 | 1 | 0 | 5 | 59954.0 | 419.9 | 30670.0 | 0 | 1017.0 |
| 6 | 1007 | 1 | 4 | 0 | 4 | 60563.0 | 259.7 | 37089.0 | 1 | 970.0 |
| 7 | 1008 | 1 | 2 | 1 | 4 | 73363.0 | 204.2 | 25311.0 | 1 | 1010.0 |
| 8 | 1009 | 1 | 2 | 1 | 3 | 56375.0 | 421.1 | 19240.0 | 1 | 999.0 |
| 9 | 1010 | 1 | 1 | 0 | 2 | 70445.0 | 256.0 | 28365.0 | 0 | 1065.0 |
6.3 Method Chaining and Summary Estimates
pandas lets you chain steps together, similar to the pipe %>% in R. Here we calculate the mean of every numeric column:
average_values = ( household .select_dtypes("number") # keep numeric columns .mean() # mean of each column (missing values are skipped) ) average_values.round(2)
hhnum 1005.5 nonmetro 0.5 Region 1.8 Rural 0.6 Household_size 3.4 Income_hhavg_r 61337.4 pctpovguidehh_r 323.1 povthresholh_hh 24424.2 Selfemployment 0.6 exprentmrtg_r 1111.5 dtype: float64
6.4 Create a New Row
Let us add the averages as a new row at the bottom of the table.
new_row = average_values.to_frame().T # turn the averages into a one-row table household_with_avg = pd.concat([household, new_row], ignore_index=True) household_with_avg.tail()
| hhnum | nonmetro | Region | Rural | Household_size | Income_hhavg_r | pctpovguidehh_r | povthresholh_hh | Selfemployment | exprentmrtg_r | |
|---|---|---|---|---|---|---|---|---|---|---|
| 6 | 1007.0 | 1.0 | 4.0 | 0.0 | 4.0 | 60563.0 | 259.7 | 37089.0 | 1.0 | 970.0 |
| 7 | 1008.0 | 1.0 | 2.0 | 1.0 | 4.0 | 73363.0 | 204.2 | 25311.0 | 1.0 | 1010.0 |
| 8 | 1009.0 | 1.0 | 2.0 | 1.0 | 3.0 | 56375.0 | 421.1 | 19240.0 | 1.0 | 999.0 |
| 9 | 1010.0 | 1.0 | 1.0 | 0.0 | 2.0 | 70445.0 | 256.0 | 28365.0 | 0.0 | 1065.0 |
| 10 | 1005.5 | 0.5 | 1.8 | 0.6 | 3.4 | 61337.4 | 323.1 | 24424.2 | 0.6 | 1111.5 |
6.5 Create a New Column
Now we add a column that labels each row.
row_identifiers = [f"No{i}" for i in range(1, len(household) + 1)] + ["Average"] household_with_avg["Variable"] = row_identifiers household_with_avg.tail()
| hhnum | nonmetro | Region | Rural | Household_size | Income_hhavg_r | pctpovguidehh_r | povthresholh_hh | Selfemployment | exprentmrtg_r | Variable | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 6 | 1007.0 | 1.0 | 4.0 | 0.0 | 4.0 | 60563.0 | 259.7 | 37089.0 | 1.0 | 970.0 | No7 |
| 7 | 1008.0 | 1.0 | 2.0 | 1.0 | 4.0 | 73363.0 | 204.2 | 25311.0 | 1.0 | 1010.0 | No8 |
| 8 | 1009.0 | 1.0 | 2.0 | 1.0 | 3.0 | 56375.0 | 421.1 | 19240.0 | 1.0 | 999.0 | No9 |
| 9 | 1010.0 | 1.0 | 1.0 | 0.0 | 2.0 | 70445.0 | 256.0 | 28365.0 | 0.0 | 1065.0 | No10 |
| 10 | 1005.5 | 0.5 | 1.8 | 0.6 | 3.4 | 61337.4 | 323.1 | 24424.2 | 0.6 | 1111.5 | Average |
6.6 Rearrange the Columns
Move the Variable column to the front.
cols = ["Variable"] + [c for c in household_with_avg.columns if c != "Variable"] household_with_avg = household_with_avg[cols] household_with_avg.tail()
| Variable | hhnum | nonmetro | Region | Rural | Household_size | Income_hhavg_r | pctpovguidehh_r | povthresholh_hh | Selfemployment | exprentmrtg_r | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 6 | No7 | 1007.0 | 1.0 | 4.0 | 0.0 | 4.0 | 60563.0 | 259.7 | 37089.0 | 1.0 | 970.0 |
| 7 | No8 | 1008.0 | 1.0 | 2.0 | 1.0 | 4.0 | 73363.0 | 204.2 | 25311.0 | 1.0 | 1010.0 |
| 8 | No9 | 1009.0 | 1.0 | 2.0 | 1.0 | 3.0 | 56375.0 | 421.1 | 19240.0 | 1.0 | 999.0 |
| 9 | No10 | 1010.0 | 1.0 | 1.0 | 0.0 | 2.0 | 70445.0 | 256.0 | 28365.0 | 0.0 | 1065.0 |
| 10 | Average | 1005.5 | 0.5 | 1.8 | 0.6 | 3.4 | 61337.4 | 323.1 | 24424.2 | 0.6 | 1111.5 |
6.7 Filter, Sort, and Group
Three of the most useful pandas operations are filtering rows, sorting, and summarizing by groups. We use the simulated household data from above.
# Filter: households with income above $60,000 high_income = household[household["Income_hhavg_r"] > 60000] print("High-income households:", len(high_income)) # Sort: largest rent or mortgage expense first household.sort_values("exprentmrtg_r", ascending=False).head(3)
High-income households: 5
| hhnum | nonmetro | Region | Rural | Household_size | Income_hhavg_r | pctpovguidehh_r | povthresholh_hh | Selfemployment | exprentmrtg_r | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1001 | 0 | 1 | 0 | 2 | 83061.0 | 305.7 | 23674.0 | 1 | 1413.0 |
| 3 | 1004 | 0 | 1 | 1 | 6 | 68276.0 | 465.8 | 29806.0 | 0 | 1381.0 |
| 2 | 1003 | 0 | 4 | 1 | 1 | 54318.0 | 322.5 | 13411.0 | 1 | 1184.0 |
# Group: average income and household size by region (household .groupby("Region") .agg(households=("hhnum", "count"), avg_income=("Income_hhavg_r", "mean"), avg_size=("Household_size", "mean")) .round(1))
| households | avg_income | avg_size | |
|---|---|---|---|
| Region | |||
| 1 | 6 | 61459.2 | 3.7 |
| 2 | 2 | 64869.0 | 3.5 |
| 4 | 2 | 57440.5 | 2.5 |
6.8 Exporting
Files are saved to your working directory. Setting index=False leaves out the row numbers.
household.to_csv("household.csv", index=False) # CSV file household.to_csv("household.txt", index=False, sep=" ") # space-delimited text file household.to_excel("household.xlsx", index=False) # Excel file (needs openpyxl) print("Files saved:", [f for f in os.listdir() if f.startswith("household")])
Files saved: ['household.xlsx', 'household.txt', 'household.csv']
7 Data Visualization
7.1 Simple Graphing
We will use matplotlib, the most common plotting package. Let us start with a histogram.
rng = np.random.default_rng(1) data = rng.normal(loc=0, scale=1, size=500) # 500 draws from a standard normal plt.hist(data, bins=15, edgecolor="white") plt.title("Histogram of data") plt.show() plt.hist(data, bins=15, density=True, edgecolor="white") # total area equals 1 plt.axvline(data.mean(), color="red", linewidth=4) # vertical line at the mean plt.title("Histogram (density) with the mean") plt.show()
Now a boxplot:
plt.boxplot(data) plt.axhline(data.mean(), color="blue", linewidth=2) # horizontal line at the mean plt.title("Creative Title") plt.ylabel("A y-axis label (with units)") plt.show()
Now let us generate some data for scatter and line plots.
x = np.arange(1, 101) y = x * 2 plt.scatter(x, y) # scatter plot plt.show() # again, but fancier plt.scatter(x, y, marker="D", s=30, color="purple") # marker shape, size, and color plt.title("Scatter plot") plt.xlabel("Predictor (x)") plt.ylabel("Response (y)") plt.show() # this looks better as a line plot plt.plot(x, y, color="purple") plt.title("Line plot") plt.xlabel("Predictor (x)") plt.ylabel("Response (y)") plt.show()
7.2 Plotting Functions
x = np.arange(0, 10.01, 0.01) y1 = 2 * x + 1 # y1 = 2x + 1 y2 = 2 * x**2 + 3 * x + 1 # y2 = 2x^2 + 3x + 1 y3 = x**3 + 2 * x**2 - 3 # y3 = x^3 + 2x^2 - 3 plt.plot(x, y1, color="blue"); plt.title("y1 = 2x + 1"); plt.show() plt.plot(x, y2, color="purple"); plt.title("y2 = 2x^2 + 3x + 1"); plt.show() plt.plot(x, y3, color="red"); plt.title("y3 = x^3 + 2x^2 - 3"); plt.show()
7.3 Multiple Graphs
fig, ax = plt.subplots(figsize=(7, 4.5)) ax.plot(x, y1, color="purple", linewidth=3, label="Linear") ax.plot(x, y2, color="blue", linewidth=3, label="Quadratic") ax.plot(x, y3, color="red", linewidth=3, label="Polynomial") ax.set_xlim(0, 10) ax.set_ylim(-10, 50) ax.set_title("Figure. Graph of functions") ax.set_xlabel("x") ax.set_ylabel("y") ax.legend(loc="upper right", ncol=2) plt.show() # set_title: title of the graph set_xlabel / set_ylabel: axis labels # color: line color linewidth: line width # set_xlim / set_ylim: axis limits legend: adds the legend
7.4 Export High Quality Figures
Higher resolution (dpi) means sharper figures but bigger files.
fig.savefig("Figure_functions.png", dpi=300, bbox_inches="tight") # PNG fig.savefig("Figure_functions.pdf", bbox_inches="tight") # PDF # fig.savefig("Figure_functions.tiff", dpi=1200) # TIFF, very large file print("Saved:", [f for f in os.listdir() if f.startswith("Figure_functions")])
Saved: ['Figure_functions.pdf', 'Figure_functions.png']
7.5 Bar Charts
Bar charts compare values across categories, such as revenue per acre by crop:
crop_names = ["Corn", "Soybeans", "Wheat", "Sorghum"] revenue_acre = [180 * 4.25, 55 * 10.90, 50 * 5.60, 95 * 4.05] plt.bar(crop_names, revenue_acre, color=["#2a5298", "#3c8d5a", "#c9a227", "#a0522d"]) plt.ylabel("Revenue ($ per acre)") plt.title("Revenue per acre by crop") plt.show()
7.6 Supply and Demand
Let us plot linear demand $Q_d = 100 - 8P$ and supply $Q_s = 20 + 12P$, then mark the market equilibrium where $Q_d = Q_s$:
P = np.linspace(0, 10, 100) Qd = 100 - 8 * P Qs = 20 + 12 * P p_eq = (100 - 20) / (8 + 12) # solve 100 - 8P = 20 + 12P q_eq = 100 - 8 * p_eq print(f"Equilibrium price: {p_eq:.2f}, quantity: {q_eq:.2f}") plt.plot(Qd, P, label="Demand", color="#2a5298", linewidth=2) plt.plot(Qs, P, label="Supply", color="#c0392b", linewidth=2) plt.scatter([q_eq], [p_eq], color="black", zorder=3) plt.annotate(f"Equilibrium ({q_eq:.0f}, {p_eq:.2f})", (q_eq, p_eq), textcoords="offset points", xytext=(10, -15)) plt.xlabel("Quantity") plt.ylabel("Price") plt.xlim(0, 110) plt.ylim(0, 10) plt.legend() plt.title("Market equilibrium") plt.show()
Equilibrium price: 4.00, quantity: 68.00
7.7 Mapping with Python
For maps we use plotly, which draws interactive maps of US states without downloading any boundary files. The values below are randomly generated for practice. Run these cells in Google Colab, or install plotly first with pip install plotly.
import plotly.express as px states = ["NE", "KS", "OK", "TX", "LA", "MO", "AR", "IA", "MN", "WI", "IL", "MI", "IN"] rng = np.random.default_rng(123) state_data = pd.DataFrame({ "state": states, "value": rng.integers(1000, 100000, len(states)), # example values }) fig = px.choropleth(state_data, locations="state", locationmode="USA-states", color="value", scope="usa", color_continuous_scale="Greens", title="Selected US States (example data)") fig.show()
County-level maps, like the Kansas map in the R notes, need county boundary files. The geopandas package can read the US Census cartographic boundary files directly from the web:
# !pip install geopandas import geopandas as gpd url = "https://www2.census.gov/geo/tiger/GENZ2023/shp/cb_2023_us_county_20m.zip" counties = gpd.read_file(url) kansas = counties[counties["STATEFP"] == "20"] # 20 is the FIPS code for Kansas ax = kansas.plot(column="AWATER", cmap="Blues", edgecolor="black", legend=True, figsize=(9, 5)) ax.set_title("Water Area at County Level in Kansas") ax.set_axis_off() plt.show()
8 Regression and Summary Tables
We use statsmodels, the standard Python package for regressions. It is already installed in Google Colab; elsewhere install it with pip install statsmodels. To keep the example self-contained, we first simulate a small farm dataset.
rng = np.random.default_rng(42) n = 200 farms = pd.DataFrame({ "fertilizer": rng.uniform(50, 200, n), # lbs of nitrogen per acre "rainfall": rng.uniform(15, 40, n), # inches during the season "irrigated": rng.integers(0, 2, n), # 1 if the field is irrigated }) farms["yield_bu"] = (60 + 0.35 * farms["fertilizer"] + 1.5 * farms["rainfall"] + 20 * farms["irrigated"] + rng.normal(0, 15, n)) # corn yield, bu/acre farms["high_yield"] = (farms["yield_bu"] > 160).astype(int) # 1 if yield > 160 farms.describe().round(2)
| fertilizer | rainfall | irrigated | yield_bu | high_yield | |
|---|---|---|---|---|---|
| count | 200.00 | 200.00 | 200.00 | 200.00 | 200.00 |
| mean | 124.08 | 27.48 | 0.52 | 153.68 | 0.40 |
| std | 42.35 | 7.21 | 0.50 | 25.70 | 0.49 |
| min | 51.10 | 15.31 | 0.00 | 78.13 | 0.00 |
| 25% | 87.83 | 20.92 | 0.00 | 137.34 | 0.00 |
| 50% | 121.85 | 27.64 | 1.00 | 153.46 | 0.00 |
| 75% | 162.09 | 34.16 | 1.00 | 170.44 | 1.00 |
| max | 198.86 | 39.67 | 1.00 | 213.63 | 1.00 |
8.1 Regression with Matrix Algebra
Before using a regression package, it helps to see what it does. The OLS coefficients solve $\hat\beta = (X'X)^{-1}X'y$, which we can compute with the matrix tools from earlier:
X = np.column_stack([np.ones(n), farms[["fertilizer", "rainfall", "irrigated"]]]) # add an intercept column y = farms["yield_bu"].to_numpy() beta = np.linalg.solve(X.T @ X, X.T @ y) # solves (X'X) b = X'y pd.Series(beta, index=["Intercept", "fertilizer", "rainfall", "irrigated"]).round(3)
Intercept 59.386 fertilizer 0.336 rainfall 1.598 irrigated 16.820 dtype: float64
The estimates are close to the values we used to simulate the data (0.35, 1.5, and 20). They are not exact because of the random noise we added, which is exactly what happens with real data.
8.2 Linear Regression
import statsmodels.formula.api as smf lm1 = smf.ols("yield_bu ~ fertilizer", data=farms).fit() # Model 1 print(lm1.summary())
8.3 Multiple Linear Regression and Probit
linear1 = smf.ols("yield_bu ~ fertilizer + rainfall + irrigated", data=farms).fit() linear2 = smf.ols("yield_bu ~ fertilizer + rainfall", data=farms).fit() probit = smf.probit("high_yield ~ fertilizer + rainfall + irrigated", data=farms).fit() # A side-by-side summary table, similar to stargazer in R from statsmodels.iolib.summary2 import summary_col table = summary_col([linear1, linear2, probit], model_names=["OLS (1)", "OLS (2)", "Probit"], stars=True, float_format="%.3f") print(table) # Save the table as an HTML file you can open in Word with open("regression_table.html", "w") as f: f.write(table.as_html())