Exploratory Data Analysis


Exploratory Data Analysis

Maria
Welcome to our lecture on exploratory data analysis. We’ll use a Toyota car dataset to explore categorical variables with frequency tables and two-way tables, then turn table counts into joint, marginal, and conditional probabilities. After that, we’ll look at correlation as a way to study relationships between numerical variables.

Michael
Before we can analyze anything, we need to bring the data into Python. The lecture uses Spyder, but the key steps are familiar pandas operations: import the libraries, load the CSV, and prepare a working copy so our analysis does not alter the original.

Maria
First, import `os` to change the working directory and `pandas` as `pd` to work with the data frame. The `os.chdir` command takes the path to the directory containing the file. Then `pd.read_csv` reads `Toyota.csv`; setting `index_col=0` uses the first column as the index.

Michael
There’s also an important missing-data detail. In this dataset, question marks are used where values are missing, but a question mark is just a string to Python. Passing `na_values='?'` to `read_csv` tells pandas to treat those entries as missing values, so pandas’ missing-data tools can handle them.

Maria
Once the data is loaded, create a separate copy with the data frame’s `.copy()` method—for example, `cars_data2 = cars_data.copy()`. We can make changes to `cars_data2` and still compare it with the original `cars_data` if we need to check our work.

Michael
Now let’s start with a frequency table. It summarizes how often each category of one categorical variable occurs. In pandas, `pd.crosstab` can create frequency tables; provide the variable of interest as the `index` argument.

Maria
For example, `pd.crosstab(index=cars_data2['FuelType'], dropna=True)` counts the observed categories of fuel type while excluding missing values. The lecture reports 1,436 rows originally and 1,336 records after missing fuel-type values are removed, so 100 records are excluded from this particular frequency count.

Michael
The reported fuel categories are CNG, diesel, and petrol. Their frequencies are 15, 144, and 1,177, respectively. That makes petrol the most common fuel type in this dataset—though this describes these records, not necessarily every set of cars.

Maria
A two-way table extends the idea to two categorical variables. It lets us examine how the categories of one variable are distributed across the categories of another. We can use `pd.crosstab` again, putting one variable in `index` and the other in `columns`.

Michael
Here, the gearbox variable is called `Automatic`: 0 represents a manual gearbox and 1 represents an automatic gearbox. Put `Automatic` in `index` and `FuelType` in `columns`, and use `dropna=True` so the table counts only rows with observed values for both variables.

Maria
That setup means rows represent gearbox type and columns represent fuel type. In the output, the manual-gearbox row includes 15 CNG cars and 144 diesel cars. The automatic-gearbox row has zero CNG and zero diesel cars; in this dataset, automatic cars are shown with petrol fuel.

Michael
The same counts can be expressed as probabilities rather than raw numbers. A joint probability is the probability that two events occur together—for example, that a car has a manual gearbox and uses CNG. In `pd.crosstab`, `normalize=True` converts the table’s counts into proportions of the overall table total.

Maria
So the joint probability for manual gearbox and CNG is reported at about 0.01, while the joint probability for manual gearbox and petrol is about 0.82. A zero in the automatic-and-CNG or automatic-and-diesel cells means those combinations do not appear in the analyzed records. These are empirical results from this dataset.

Michael
Next are marginal probabilities: probabilities for one event considered on its own, rather than a particular combination. Add `margins=True` to the crosstab to include row and column totals, labeled `All`; with `normalize=True`, those totals are expressed as proportions.

Maria
For instance, the lecture interprets a row total of about 0.9469 as the proportion of records with a manual gearbox across the fuel categories. A column total of about 0.88 is interpreted as the proportion of cars using petrol across gearbox types. The marginal probabilities across all categories sum to one.

Michael
Conditional probability asks about one event given that another event has occurred. With `normalize='index'`, each row is normalized to sum to one. That answers questions such as: given the gearbox type, what is the probability of each fuel type?

Maria
For manual cars, the reported probabilities are about 0.01 for CNG, 0.11 for diesel, and 0.87 for petrol. So, among manual cars in this dataset, petrol is the most likely fuel type. For automatic cars, the reported probabilities are zero for CNG and diesel and one for petrol.

Michael
We can reverse the conditioning direction with `normalize='columns'`. Now each column sums to one, answering: given the fuel type, what is the probability of each gearbox type? For CNG, the observed cars all have manual gearboxes, so the conditional probability of manual given CNG is one.

Maria
For petrol, the lecture reports a probability of about 0.93 for a manual gearbox when the fuel type is known to be petrol. The key is to read the normalization direction carefully: index normalization conditions on the row variable, while column normalization conditions on the column variable.

Michael
So far, we’ve focused on categorical variables. When both variables are numerical, the lecture introduces correlation to describe the strength and direction of their association. A scatter plot gives a visual view: an upward trend suggests a positive relationship, while a downward trend suggests a negative one.

Maria
If the scatter plot has no clear pattern and the points are spread about without a trend, that suggests little or no correlation. For example, if heavier cars tend to cost more, weight and price would show a positive trend. If older cars tend to cost less, age and price would show a negative trend.

Michael
A correlation coefficient is bounded between minus one and plus one. Values near plus one indicate a strong positive association, values near minus one indicate a strong negative association, and a value near zero indicates little or no linear correlation. The lecture offers above 0.7 as a rule of thumb for a fair correlation, while emphasizing that direction comes from the sign.

Maria
To calculate correlations in pandas, select the numerical columns and apply `.corr()`. The lecture first excludes columns with the `object` data type, saving the result as a numerical data frame. It reports 1,436 observations and eight numerical variables after this selection.

Michael
Calling `numerical_data.corr()` computes pairwise correlations between the numerical columns. Pairwise means that the association is calculated for each pair of variables, and pandas excludes missing values from each calculation. The default method is Pearson correlation, which measures the strength of association between numerical variables.

Maria
In the resulting correlation matrix, the diagonal entries are all one because each variable is perfectly correlated with itself. The lecture’s example gives price and age a correlation of about negative 0.87: as age increases, price tends to decrease, a strong negative association.

Michael
Price and kilometre have a negative correlation of roughly negative 0.57, meaning cars with more kilometres tend to have lower prices in these data. Weight and price have a positive correlation of about 0.58, while age and kilometre have a positive association around 0.5: older cars tend to have accumulated more kilometres.

Maria
Pearson is the method used in this example. The lecture notes that Kendall’s rank correlation and Spearman’s rank correlation are alternatives when working with ordinal variables. In pandas, a different correlation method can be specified through the `method` argument.

Michael
Let’s recap the path we took: we loaded the Toyota data, treated question marks as missing values, and protected the original by making a copy. We used frequency tables to summarize one categorical variable and two-way tables to examine two categorical variables.

Maria
Then we used normalization and margins to interpret joint, marginal, and conditional probabilities, paying attention to which rows or columns sum to one. Finally, we used scatter plots and correlation coefficients to describe the direction and strength of relationships between numerical variables. That completes our tour of the lecture’s main tools for exploratory data analysis.

Ask anything
We've read this whole study set, so questions about it get the best answers.