Docsity

Computer Science for Economics (STATA, Python & Pandas), Appunti di Elementi di Informatica

Toggle sidebar
bg1
Computer Science 2025/2026
StataNow
Stata is a statistical software package used for data management, statistical analysis, and graphics.
- Pros: It is easy to use, widely adopted in the econometrics community, offers good graphing
capabilities, and combines a graphical user interface (GUI) with command lines and scripts.
- Cons: It is commercial (paid) software, can only work with one dataset in memory at a time, and is less
powerful outside the field of econometrics
How does Stata work?
You can enter the commands in 3 ways:
1. interactively: through the top menu. Go to the menu
→
file open
→
2. manually:Typing specific commands in the terminal
window (e.g., typing use followed by the file path).
3. do-file: text file containing a saved list of computer
instructions (commands) that you can run all at once.
Stata datasets are saved as .dta files.
Commands
COMMAND
DESCRIPTION
browse or br
Opens the data editor to view the data as a
spreadsheet
describe
helps understand the structure of the data before
starting the analysis
summarize or sum
provides descriptive statistics for the variables
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Anteprima parziale del testo

Scarica Computer Science for Economics (STATA, Python & Pandas) e più Appunti in PDF di Elementi di Informatica solo su Docsity!

Computer Science 2025/

StataNow

Stata is a statistical software package used for data management, statistical analysis, and graphics.

  • Pros: It is easy to use, widely adopted in the econometrics community, offers good graphing capabilities, and combines a graphical user interface (GUI) with command lines and scripts.
  • Cons: It is commercial (paid) software, can only work with one dataset in memory at a time, and is less powerful outside the field of econometrics

How does Stata work?

You can enter the commands in 3 ways:

1. interactively : through the top menu. Go to the menu → file → open 2. manually :Typing specific commands in the terminal window (e.g., typing use followed by the file path). 3. do-file : text file containing a saved list of computer instructions (commands) that you can run all at once. Stata datasets are saved as .dta files.

Commands

COMMAND DESCRIPTION

browse or br Opens the data editor to view the data as a spreadsheet

describe helps understand the structure of the data before starting the analysis

summarize or sum provides descriptive statistics for the variables

tabulate creates frequency tables, summarizing how many observations fall into each category of a specific variable.

Evidence can be comprehended:

- graphically

  • computing correlations between two variables

Scatter plot

A scatter plot is a graph used to show the relationship between two quantitative variables by plotting one on the x-axis and the other on the y-axis.

Computing correlations

correlate or corr - command that calculates the Pearson correlation coefficient. This coefficient

measures the strength and direction of a linear relationship: it ranges from -1 to +1 , and a value of 0 means there is no linear relationship at all.

How to save?

  1. Type log using filename.log before starting your analysis. This log file saves all your work, recording both the commands executed and the output produced.
  2. Type log close at the end to stop recording.

The log file saves all your work, recording both the commands executed and the output produced by Stata.

Help

Type help command_name to ask for help when you don't know how to use a specific command.

Excel file

Files in .xls format. To import excel files on Stata, we can use 2 ways:

1. Interactively : file - import - excel spreadsheet 2. Manually : using import excel "filename.xlsx"

Text and .CSV data

To import a text file manually (like .txt or .csv ) into StataNow, use the

import delimited command.

Interactively, you click file - import - text data.

Potential problems you can face importing files:

- variable names : for example, Stata doesn’t accept names starting with numbers. To solve this problem, you change the name before in excel, text or csv. **- characters

  • missing values** : Stata might import numbers as text strings. Use the destring command to convert them back into numeric variables. - size : If the dataset is too big, use the compress command to save memory

○ by prefix : adding the by prefix before a standard command alters its execution scope. Instead of applying the command to the entire dataset at once, it forces the command to execute independently on distinct subsets of the data, categorized by a specific grouping variable. ○ sort : sort data by grouping variable

Summarize

The collapse command converts the entire dataset into group-level statistics.

In order to create a summarized dataset while protecting the original data in memory, you have to type:

- preserve : takes a temporary snapshot of the currently dataset - collapse command - save + name.dta : saves the new summarize dataset - restore : recovers the original dataset that was temporarily saved, bringing it back into memory. In Stata, the preserve and restore commands are used together to temporarily save and then recover the dataset in memory.

Merge two dataset

If you have two datasets with the same set of variables, to combine them vertically use the command append.

  1. open dataset 1 2. append using data2.dta
  2. observations from data 2 are below data 1

To combine them horizontally based on a shared key variable, use the command merge. To do this, Stata works with two files:

**- Master dataset

  • Using dataset**

There are different types of merge:

- merge 1:1 - t is used when each key value appears only once in both dataset merge 1:1 varlist using filename.dta - merge m:1 (many-to-one) - It is used when you have many observations for a specific key in your Master dataset, but only one observation for that key in the Using dataset. merge m:1 varlist using filename.dta - merge 1:m (one-to-many) - it is used when you have one observation for the Master dataset and many for the Using dataset. merge 1:m varlist using filename.dta

Each time you run this command, Stata automatically generates a new variable called _merge to tell you how the merge operation went. It's essential to check this before trusting the merged dataset, using the command

check_merge.

You can add optional parameters after the command merge.

- nogen - prevents Stata from automatically creating the merge control column at the end of the operation. You use it when you're absolutely sure your data matches perfectly and don't want to "clutter" your dataset with extra variables you don't need. **- keep ()** - you use it to say to Stata what to keep and what not. **- update_** - it will fill the missing values in Master with Using

  • update replace - if information exists in both files, the data coming from the Using file erases and replaces the old data you had in the Master file.

- assert () - it is used to see if every observation has a perfect match. If it doesn’t find it, Stata crashes, gives you an error, and aborts the code. You use it when one data is missing and you don’t want to ruin everything.

Regression vs. Correlation

Correlation indicates that two variables move together, while regression specifies how much one variable changes when the other changes.

Regression aims to find the straight line that best summarizes the relationship between two variables on a scatterplot. A straight line is used because it is the simplest relationship, acts as a good first approximation, and is easy to interpret.

To run a regression, you use the command regress followed by the dependent variable first, and then the independent variable(s). For example: regress varlist [weight] [if exp] [in range] [, options] You can also use the command robust at the end of the command, in order to make statistical tests reliable when the variance of the errors is not constant.

Ordinary Least Squares OLS

OLS is the principle used to find this "best" line. It works by minimizing the sum of the squared vertical distances between the actual data points and the line. These vertical distances are called residuals or errors. We use a straight line because: it is simpler, it’s easy to interpret, and it often provides a good approximation.

The residuals are squared because

  • it penalizes large errors more heavily
  • prevents positive and negative errors from canceling each other out
  • creates a U-shaped mathematical function that guarantees a single unique minimum point (a unique optimal line).

Interpreting Regression Output

When Stata produces a regression table, you must understand several key metrics: ● Number of obs: This indicates the sample size (how many observations the regression is based on). ● R-squared: This measures the "goodness of fit" and represents the percentage of variation in the dependent variable that is explained by the model. ● Coefficient: This is the slope of the fitted line. It represents the average change in the dependent variable when the independent variable increases by one unit, holding all other variables constant. ● P-value (Statistical Significance): This indicates whether the effect is statistically significant. If the true effect were zero, the p-value shows the probability of observing an estimate this large or larger. A very low p-value (eg, 0.001) means you can reject the null hypothesis and conclude there is strong statistical evidence of an association. ● Control Variables: These are additional variables included in the regression to hold other factors constant, which helps better isolate the specific effect of the variable of interest.

Python

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It is precise. Python is a high-level and interpreted programming language, so it handles the complicated computer hardware for you, letting you write clear instructions that run step-by-step so you can see your results instantly.

● .py file: A simple text file containing only code. Professionals use these for large software projects.

● .ipynb (Notebook): It's a document that mixes code, text, and charts. It's the standard for Data

Science and Economics.

Why Python? ● Automation: Executes hours of manual spreadsheet tasks in seconds. ● Reproducibility: Creates a transparent, auditable record of your analysis. ● Scalability: Processes millions of rows of data without freezing or crashing. ● Real-Time Data: Streams live market prices and economic indicators directly from the web.

Programming with Python use a basic block:

1. Input : taking in informations 2. Output : giving infos back, showing the result 3. Math : crunching the numbers 4. Conditionals : making choice 5. Repetition : doing the same chore over and over again

Print

The print(‘...’) function takes the phrase and displays it directly on the screen.

Arithmetic operators

Operators are symbols that represent computations.

Operator Description Example

  • Addition 10 + 5
  • Subtraction 10 - 2
  • Multiplication 4 * 3

/ Division 10 / 2

** Exponentiation 2 ** 3

// Floor Division 10 // 3

% Modulo (Remainder) 10 % 3

Values and types

When you give it a piece of information, it needs to know exactly what "type" of material it is dealing with so it knows how to handle it. Because of this, Python organizes information into strict categories:

  • int (Integers): These are standard whole numbers without a decimal point. You use them for counting whole things. Example: 42 , 10 , -5.
  • float (Floating-point): These are numbers with decimals. You use these when you need exact precision. Example: 3.14, 19.99.
  • str (Strings): This is simply text. It can be letters, words, or full sentences. Python only knows it is text because you wrap it inside quotation marks. Example: "Hello", "Economic data".

If you are looking at a piece of data and aren't sure what category it belongs to, you use type() to ask

Python, "What is this?". If you ask type("Hello"), Python will scan it and tell you, "This is a string (str)."

Expressions An expression is a combination of values and operators. Python follows the usual order: exponentiation → multiplication/division → addition/subtraction.

Functions

A function is a named sequence of statements that performs a computation. Python comes with many pre-written tools called built-in functions.

  • print()
  • type(): Returns the class of a value.
  • abs(): Returns the absolute value of a number.
  • round(): Rounds a number to the nearest integer.
  • name(argument): to call a function

Object-Oriented Programming OOP basics

Python is an Object-Oriented language.

● Track updates: When a variable changes, the diagram physically shows the old value being replaced by the new one. ● Model systems: Just like "current debt" defines the state of an economy, your variables define the state of your program.

Expression vs. Statement

  • An expression is a piece of code that Python can calculate to produce a value
  • A statement is a command that tells Python to do something. It performs an action but doesn't have a value itself.

Function definition

A function definition names a reusable block of code. Functions help you avoid repeating the same code, a principle called DRY (Don't Repeat Yourself). Structure:

● Header : Starts with def, ends with :

● Body : Indented lines that run when the function is called.

Parameters and arguments

To make functions flexible, we use placeholders.

● A parameter is the variable name inside the def header (the placeholder).

● An argument is the actual value you pass when you call the function.

Modules: the import statement and the dot operator

A module is a collection of variables and functions. Think of it as a toolbox you bring into your

workshop.

Use import to load one; then the dot operator. to reach inside and use its contents.

How can you know what's inside a toolbox like math?

● Use dir(module) to list all the "tools" (functions and constants) inside. ● Use help(module.name) to read the documentation for a specific tool.

When you create a variable inside a function, it is local. This means it only exists inside an isolated workspace that is created when the function starts and destroyed when it finishes.

Tracebacks

When an error occurs, Python gives you a map of the frames (stack) to show you how you got there. This is a traceback. Pro tip: Read it from bottom to top. The bottom line tells you what happened; the lines above tell you where it happened.

Comments

Everything after # on a line is a comment.

Boolean values

A Boolean is one of Python's built-in data types. It has exactly two possible values: True and False — nothing in between, no other options.

Comparison operators

Operator Meaning

== equal to

!= not equal to

<, > less than, greater than

<=, >= less/greater than or equal

⚠ == tests equality. = assigns a value.

The modulus operator

The modulus operator % computes the remainder of an integer division.

  • 7 % 3 → "how many times does 3 fit into 7 without exceeding it?" → twice (3 × 2 = 6), with 1 left over → result is 1
  • 10 % 5 → 5 fits exactly twice (5 × 2 = 10), nothing left over → result is 0
  • 9 % 2 → 2 fits four times (2 × 4 = 8), with 1 left over → result is 1

Logical operators combine or modify Boolean values, letting you express compound conditions in a single expression.

● and — True only when both sides are True. If either side is False, the whole expression is False.

Think: "condition A and condition B must both hold."

● or — True when at least one side is True. It is False only if both sides are False. Think: "condition A or

condition B (or both) must hold."

● not — takes a single Boolean and reverses it. not True → False; not False → True. Think: "the

opposite of this condition."

If / else

An if statement is how Python makes decisions. It runs a block of code only when a specified condition is True, and skips it otherwise.

An else clause attaches an alternative body to an if statement. Together they create two mutually exclusive branches:

● The if body runs when the condition is True.

● The else body runs when the condition is False.

Elif

elif is short for "else if". It extends an if statement to handle more than two possible cases without having to nest multiple if blocks. Python evaluates the branches from top to bottom and runs the body of the first branch whose condition is True — then immediately skips the rest, even if later conditions would also be True. This top-to-bottom, first-match-wins behaviour means order matters.

Error Handling (Try / Except)

Sometimes, user input or corrupted data can cause your program to crash (for example, trying to run

int("apple") will cause a ValueError). To prevent the program from stopping, Python uses Try-Except blocks.

● try: Python will attempt to execute the code inside this block.

● Stub — a minimal function that does almost nothing (usually just return 0.0 or return None), but at

least runs without errors. Writing a stub first confirms that the function name, parameters, and call are all correct before you touch the logic.

● Scaffolding — temporary print statements added during development to inspect intermediate values

and verify each step. Scaffolding is removed once the function works correctly; it is not part of the final product.

The strategy in four steps:

1. Write a stub, confirm it runs.

2. Add one piece of logic, add scaffolding, test.

3. Repeat step 2 until complete.

4. Remove all scaffolding.

Checking types

isinstance(value, type) is Python's built-in function for checking whether a value belongs to a given

type. It returns True if value is an instance of type, and False otherwise.

Input validation means checking, at the very start of a function, that the arguments it receives actually make sense — before any computation runs. Without validation, a bad argument can cause an error deep inside the function with a confusing traceback.

Loop variable

A for loop repeats an action for each item in a sequence. The variable defined in the loop header is called the loop variable.

When you need to loop a fixed number of times, use range() instead of writing a list by hand.

  • range() is memory-efficient: it doesn't create the whole list in memory, it generates one number at a time.

Update

An update gives a new value to an existing variable based on its old value.

  • Counter — a variable that increases by 1 each time a condition is met. Used to count how many items satisfy a criterion.
  • Accumulator — a variable that accumulates (adds up) values across iterations. Used to compute sums, running totals, or products.

In operator

in checks whether one string is a substring of another — no loop needed.

Combined with lower(), it gives case-insensitive search.

Linear search

Linear search : loop through a sequence; return as soon as you find what you need (short-circuit); return a default at the end.

The return True inside the loop exits immediately when the condition is met — the return False at the

end only runs if nothing matched.

while loops

A while loop repeats as long as a condition is True — useful when you don't know the number of iterations in

advance. Always ensure the condition eventually becomes False — otherwise you get an infinite loop.

break and continue

● break — exits the loop immediately

● continue — skips the rest of the current iteration and goes back to the condition

File Handling (Reading and Writing Files)

Before you can analyze data, you often need to open raw text files. You interact with files using the open() function, which creates a "file handle" (a pointer allowing Python to interact with the file).

● Reading (mode='r'): fhand = open("data.txt", "r"). You can read the entire file at once using .read(), or you can efficiently read it line-by-line using a loop (for line in fhand:). ● Writing (mode='w'): fout = open("new_file.txt", "w"). This allows you to write new data into a file using fout.write(). Warning: Opening an existing file in 'w' mode will completely erase its previous contents! ● Cleaning lines: Text files often contain hidden "newline" characters (\n) at the end of every row. Use the .rstrip() string method to strip these invisible characters away while reading.

Data structures

A data structure is a way to organise, store, and access data so that your programs can work with it efficiently. Python provides several built-in data structures that are extremely versatile. However, there are many other data structures that are tailored for specific contexts. These are often introduced by library extensions to handle data more efficiently in certain domains.

Data structure Syntax Mutable? Typical use case String (str) 'hello'^ No Ticker symbols, country names, labels List (list) [1, 2, 3] (^) Yes GDP growth rates, portfolios, any ordered collection

Tuple (tuple) (1,^ 2,^ 3)^ No Fixed records — e.g. ('Italy', 2023, 1.2)

Set (set) {1,^ 2,^ 3}^ Yes Unique elements — e.g. sectors in a portfolio

Dictionary (dict) {'key': value} Yes Look-up tables — e.g. ticker → price

String

A string (str) is a built-in data structure used to hold text. It is a sequence that can only contain characters like letters, digits, and symbols. Because strings are sequences, you can navigate them using three main actions: ● Indexing: Grab a single character by its position using brackets (e.g., ticker[0] gets the first letter). ● Slicing: Grab a chunk of text (e.g., word[0:2]). ● Iteration: Loop through the text character by character.

Strings are immutable , meaning their internal contents cannot be changed once created.

Loop through the dictionary to extract, transform, or filter data. .items() gives you both the key and the value at each step.

Pandas

Pandas is a free, open-source Python library designed specifically for data manipulation and analysis, particularly when working with numerical tables and time series.

To start using it in your code, the standard convention is to load the package using the alias pd by running

import pandas as pd.

At its core, Pandas organizes data into two primary structures.

  • A Series is a one-dimensional, indexed array that contains homogeneous data.
  • A DataFrame is a two-dimensional structure—very much like a standard Excel spreadsheet or an SQL database table—that can hold non-homogeneous data (like integers, text strings, and decimals) across its different columns. When you extract a single column from a DataFrame, the resulting object is a Series.

Getting Data In and Out

Pandas makes it easy to transform real-world data files directly into DataFrames. To load information, you use "read" functions:

  • pd.read_csv() for CSV files
  • pd.read_excel() for Excel spreadsheets

Conversely, you can save your manipulated DataFrames back out to files using "to" methods, such as .to_excel(). When saving files, you can use parameters like index = False to prevent Pandas from

exporting the row indexes as a new column.

Data Inspection Toolkit

Command Type Description

.head(n) / .tail(n) Method Returns the first or last n rows of the DataFrame.

.shape Attribute^ Returns the dimensions of your data, showing the number of rows and columns.

.dtypes Attribute Displays the data type stored in each column, such as int (integers), float64 (decimals), or object (strings).

.info() Method Provides a comprehensive summary of the DataFrame, including the number of non-null (filled) entries per column, data types, and total memory usage.

.describe() Method^ Calculates statistical information for numerical columns, returning

the count, mean, standard deviation, minimum, maximum, and percentiles.

Selecting and Filtering Information

To isolate specific information, you can extract columns or filter rows based on conditions.

You can select a single column by putting its name in brackets, like df["Age"].

If you want to select multiple columns, you pass a list of names using double brackets, like df[["Age",

"Sex"]], which returns a smaller DataFrame rather than a Series.

Filtering allows you to slice the data logically. By placing a condition inside the brackets, such as

titanic[titanic["Age"] > 35], Pandas will return only the rows where that condition is true. You can

combine multiple conditions using the & (AND) or | (OR) operators, but you must wrap each individual

condition in its own set of parentheses.

Pandas also offers specialized filtering methods.

The .isin() method lets you check if a column's value matches a specific list of options. To clean up

incomplete data, the .notna() method filters out any rows where a specific field is blank or missing. Finally, if

you want to filter rows and select specific columns at the exact same time, you can use the .loc method.

Loading Data for Time Series

When loading the data using pd.read_csv(), the document introduces two helpful parameters for handling

time-based data. The index_col parameter allows you to set a specific column—such as the 'datetime'

column in this dataset—as the index of the DataFrame. Additionally, the parse_dates parameter

automatically transforms the date strings in the file into functional TimeStamp objects.

Creating Basic Plots

Visualizing data in Pandas is highly straightforward; simply attaching the .plot() method to your DataFrame will generate a graph of all your data. If you only want to see the trends for a specific location, you can apply the .plot() method to an isolated single column, such as the Paris station data. By default, Pandas will always generate a line graph unless instructed otherwise.

Exploring Different Chart Types

Pandas offers a wide variety of chart types beyond standard line graphs. For instance, if you want to see the relationship between two specific locations, you can use .plot.scatter() and define your x and y axes to

create a scatter plot comparing London and Paris. You can also add the alpha = 0.5 parameter to this

method, which makes the plotted dots 50% transparent—a highly useful trick when you have many overlapping data points. You can also use .plot.box() to generate a boxplot, or choose from a built-in list

of other methods like area, bar, pie, and histogram charts. If you ever forget what chart types are available, you can generate the complete list by running this code:

[method_name for method_name in dir(air_quality.plot) if not (method_name.startswith("_"))].

Customizing and Saving Graphs

You can easily adjust the layout of your visualizations directly within the plot method parameters. Setting subplots = True will separate each column into its own distinct graph, while figsize allows you to adjust the dimensions of the output. For deeper customization, you can use Matplotlib to create a blank figure and axes

Grouping Data with .groupby()

Often, you need to calculate statistics for specific categories within your data. The .groupby() method allows you to group data by a category before applying a statistical calculation. For instance, to find the

average age separated by gender, you would use titanic.groupby("Sex")["Age"].mean(). If you do

not specify the ["Age"] column at the end, Pandas will simply calculate the mean for every numerical column in the dataset based on gender (including columns where a mean doesn't make logical sense, like

PassengerId or Survived). You can even group by multiple columns simultaneously by passing a list, such

as calculating the mean ticket fare for each combination of sex and cabin class: titanic.groupby(["Sex", "Pclass"])["Fare"].mean().

Counting Records

Finally, if you just want to count the total number of records (rows) inside each category of a specific column,

you can use the .value_counts() method. For example, to see exactly how many passengers were in each

cabin class, you would use titanic["Pclass"].value_counts() (which reveals 491 passengers in

Class 3, 216 in Class 1, and 184 in Class 2). You can also achieve this exact same result using the grouping

method by writing titanic.groupby("Pclass")["Pclass"].count().