13. Exploratory Data Analysis#
13.1. Introduction#
This chapter will show you how to use visualisation and transformation to explore your data in a systematic way, a task that data scientists call exploratory data analysis, or EDA for short. EDA is an iterative cycle; you:
Generate questions about your data.
Search for answers by visualising, transforming, and modelling your data.
Use what you learn to refine your questions and/or generate new questions.
EDA is not a formal process with a strict set of rules and, during the initial phases of EDA, you should feel free to investigate every idea that occurs to you. Some of these ideas will pan out, and some will be dead ends. As your exploration continues, you will home in on a few particularly productive areas that you’ll eventually write up and communicate to others. As you explore your data, you should remember that there are some pitfalls: you should always think about how the data were collected, what might be missing, whether there are quality problems, and be really strict about the differences between correlation and causation (this is a huge topic in itself!).
13.1.1. Prerequisites#
For doing EDA, we’ll use the pandas, skimpy, and pandas-profiling packages. We’ll also need lets-plot for data visualisation. All of these can be installed via pip install <packagename>
.
As ever, we begin by loading these packages that we’ll use:
from skimpy import skim
import pandas as pd
from pandas.api.types import CategoricalDtype
from lets_plot import *
from lets_plot.mapping import as_discrete
LetsPlot.setup_html()
13.2. Questions#
“There are no routine statistical questions, only questionable statistical routines.” — Sir David Cox
“Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise.” — John Tukey
Your goal during EDA is to develop an understanding of your data. The easiest way to do this is to use questions as tools to guide your investigation. When you ask a question, the question focuses your attention on a specific part of your dataset and helps you decide which graphs, models, or transformations to make.
EDA is fundamentally a creative process. And like most creative processes, the key to asking quality questions is to generate a large quantity of questions. It is difficult to ask revealing questions at the start of your analysis because you do not know what insights are contained in your dataset. On the other hand, each new question that you ask will expose you to a new aspect of your data and increase your chance of making a discovery. You can quickly drill down into the most interesting parts of your data—and develop a set of thought-provoking questions—if you follow up each question with a new question based on what you find.
There is no rule about which questions you should ask to guide your research. However, two types of questions will always be useful for making discoveries within your data. You can loosely word these questions as:
What type of variation occurs within my variables?
What type of covariation occurs between my variables?
The rest of this chapter will look at these two questions. We’ll explain what variation and covariation are, and we’ll show you several ways to answer each question.
13.3. Variation#
Variation is the tendency of the values of a variable to change from measurement to measurement. You can see variation easily in real life; if you measure any continuous variable twice, you will get two different results. This is true even if you measure quantities that are constant, like the speed of light, because of deficiencies in equipment. Each of your measurements includes a small amount of error that varies from measurement to measurement. Variables can also vary if you measure across different subjects (e.g. the eye colours of different people) or different times (e.g. the energy levels of an electron at different moments). The best way to understand that pattern is to visualize the distribution of the variable’s values.
We’ll start our exploration by visualizing the distribution of weights ("carat"
) of ~54,000 diamonds from the diamonds
dataset.
diamonds = pd.read_csv(
"https://github.com/mwaskom/seaborn-data/raw/master/diamonds.csv"
)
diamonds["cut"] = diamonds["cut"].astype(
CategoricalDtype(
categories=["Fair", "Good", "Very Good", "Premium", "Ideal"], ordered=True
)
)
diamonds["color"] = diamonds["color"].astype(
CategoricalDtype(categories=["D", "E", "F", "G", "H", "I", "J"], ordered=True)
)
diamonds.head()
carat | cut | color | clarity | depth | table | price | x | y | z | |
---|---|---|---|---|---|---|---|---|---|---|
0 | 0.23 | Ideal | E | SI2 | 61.5 | 55.0 | 326 | 3.95 | 3.98 | 2.43 |
1 | 0.21 | Premium | E | SI1 | 59.8 | 61.0 | 326 | 3.89 | 3.84 | 2.31 |
2 | 0.23 | Good | E | VS1 | 56.9 | 65.0 | 327 | 4.05 | 4.07 | 2.31 |
3 | 0.29 | Premium | I | VS2 | 62.4 | 58.0 | 334 | 4.20 | 4.23 | 2.63 |
4 | 0.31 | Good | J | SI2 | 63.3 | 58.0 | 335 | 4.34 | 4.35 | 2.75 |
Since "carat"
is a numerical variable, we can use a histogram:
(ggplot(diamonds, aes(x="carat")) + geom_histogram(binwidth=0.5))
Now that you can visualize variation, what should you look for in your plots? And what type of follow-up questions should you ask? We’ve put together a list below of the most useful types of information that you will find in your graphs, along with some follow-up questions for each type of information. The key to asking good follow-up questions will be to rely on your curiosity (What do you want to learn more about?) as well as your skepticism (How could this be misleading?).
13.3.1. Typical values#
In both bar charts and histograms, tall bars show the common values of a variable, and shorter bars show less-common values. Places that do not have bars reveal values that were not seen in your data. To turn this information into useful questions, look for anything unexpected:
Which values are the most common? Why?
Which values are rare? Why? Does that match your expectations?
Can you see any unusual patterns? What might explain them?
Let’s take a look at the distribution of "carat"
for smaller diamonds.
Note that when we create smaller_diamonds
, we’re doing it by creating a copy. Otherwise, any changes we made to smaller_diamonds
would also affect diamonds
(the two point to the same underlying data in your computer’s memory). Sometimes you may want to have a cut still be connected to the original dataset, and sometimes you don’t; in this case, we’d like them to be distinct so we use copy()
.
smaller_diamonds = diamonds.query("carat < 3").copy()
(ggplot(smaller_diamonds, aes(x="carat")) + geom_histogram(binwidth=0.01))
This histogram suggests several interesting questions:
Why are there more diamonds at whole carats and common fractions of carats?
Why are there more diamonds slightly to the right of each peak than there are slightly to the left of each peak?
Visualisations can also reveal clusters, which suggest that subgroups exist in your data. To understand the subgroups, ask:
How are the observations within each subgroup similar to each other?
How are the observations in separate clusters different from each other?
How can you explain or describe the clusters?
Why might the appearance of clusters be misleading?
Some of these questions can be answered with the data while some will require domain expertise about the data. Many of them will prompt you to explore a relationship between variables, for example, to see if the values of one variable can explain the behavior of another variable. We’ll get to that shortly.
13.3.2. Unusual values#
Outliers are observations that are unusual; data points that don’t seem to fit the pattern.
Sometimes outliers are data entry errors, sometimes they are simply values at the extremes that happened to be observed in this data collection, and other times they suggest important new discoveries.
When you have a lot of data, outliers are sometimes difficult to see in a histogram.
For example, take the distribution of the "y"
variable from the diamonds dataset.
The only evidence of outliers is the unusually wide limits on the x-axis.
(ggplot(diamonds, aes(x="y")) + geom_histogram(binwidth=0.5))
There are so many observations in the common bins that the rare bins are very short, making it very difficult to see them (although maybe if you stare intently at 0 you’ll spot something).
To make it easy to see the unusual values, we need to zoom to small values of the y-axis with coord_cartesian()
:
(
ggplot(diamonds, aes(x="y"))
+ geom_histogram(binwidth=0.5)
+ coord_cartesian(ylim=[0, 50])
)
coord_cartesian()
also has an xlim()
argument for when you need to zoom into the x-axis.
Lets-Plot also has xlim()
and ylim()
functions that work slightly differently: they throw away the data outside the limits.
This allows us to see that there are three unusual values: 0, ~30, and ~60. We pluck them out with pandas:
unusual = diamonds.query("y < 3 or y > 20").loc[:, ["x", "y", "z", "price"]]
unusual
x | y | z | price | |
---|---|---|---|---|
11963 | 0.00 | 0.0 | 0.00 | 5139 |
15951 | 0.00 | 0.0 | 0.00 | 6381 |
24067 | 8.09 | 58.9 | 8.06 | 12210 |
24520 | 0.00 | 0.0 | 0.00 | 12800 |
26243 | 0.00 | 0.0 | 0.00 | 15686 |
27429 | 0.00 | 0.0 | 0.00 | 18034 |
49189 | 5.15 | 31.8 | 5.12 | 2075 |
49556 | 0.00 | 0.0 | 0.00 | 2130 |
49557 | 0.00 | 0.0 | 0.00 | 2130 |
The "y"
variable measures one of the three dimensions of these diamonds, in mm.
We know that diamonds can’t have a width of 0mm, so these values must be incorrect.
By doing EDA, we have discovered missing data that was coded as 0, which we never would have found by simply searching for NA
s.
Going forward we might choose to re-code these values as NA
s in order to prevent misleading calculations.
We might also suspect that measurements of 32mm and 59mm are implausible: those diamonds are over an inch long, but don’t cost hundreds of thousands of dollars!
It’s good practice to repeat your analysis with and without the outliers. If they have minimal effect on the results, and you can’t figure out why they’re there, it’s reasonable to omit them, and move on. However, if they have a substantial effect on your results, you shouldn’t drop them without justification. You’ll need to figure out what caused them (e.g., a data entry error) and disclose that you removed them in your write-up.
13.3.3. Exercises#
Explore the distribution of each of the
x
,y
, andz
variables indiamonds
. What do you learn? Think about a diamond and how you might decide which dimension is the length, width, and depth.Explore the distribution of
"price"
. Do you discover anything unusual or surprising? (Hint: Carefully think about thebinwidth=
keyword argument setting and make sure you try a wide range of values.)How many diamonds are 0.99 carat? How many are 1 carat? What do you think is the cause of the difference?
Compare and contrast
coord_cartesian()
vs.xlim()
orylim()
when zooming in on a histogram. What happens if you leave binwidth unset? What happens if you try and zoom so only half a bar shows?
13.4. Unusual Values#
If you’ve encountered unusual values in your dataset, and simply want to move on to the rest of your analysis, you have two options.
Drop the entire row with the strange values:
condition = ((diamonds["y"] < 3) | (diamonds["y"] > 20)) diamonds2 = diamonds.loc[~condition, :]
We don’t recommend this option because one invalid value doesn’t imply that all the other values for that observation are also invalid. Additionally, if you have low quality data, by the time that you’ve applied this approach to every variable you might find that you don’t have any data left!
Instead, we recommend replacing the unusual values with missing values. One way to do this, which makes a distinction between data frames that have had the unusual values replaced and the original data, is to make a copy and then set the problematic values to
pd.NA
, pandas’s special NA value.
diamonds2 = diamonds.copy()
condition = (diamonds2["y"] < 3) | (diamonds2["y"] > 20)
diamonds2.loc[condition, "y"] = pd.NA
It’s not obvious where you should plot missing values, so lets-plot doesn’t include them in the plot:
(ggplot(diamonds2, aes(x="x", y="y")) + geom_point())
Other times you want to understand what makes observations with missing values different to observations with recorded values.
For example, in the nycflights13 data, missing values in the "dep_time"
variable indicate that the flight was cancelled.
So you might want to compare the scheduled departure times for cancelled and non-cancelled times.
You can do this by making a new variable, using is.na()
to check if "dep_time"
is missing.
url = "https://raw.githubusercontent.com/byuidatascience/data4python4ds/master/data-raw/flights/flights.csv"
flights = pd.read_csv(url)
flights.head()
year | month | day | dep_time | sched_dep_time | dep_delay | arr_time | sched_arr_time | arr_delay | carrier | flight | tailnum | origin | dest | air_time | distance | hour | minute | time_hour | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 2013 | 1 | 1 | 517.0 | 515 | 2.0 | 830.0 | 819 | 11.0 | UA | 1545 | N14228 | EWR | IAH | 227.0 | 1400 | 5 | 15 | 2013-01-01T10:00:00Z |
1 | 2013 | 1 | 1 | 533.0 | 529 | 4.0 | 850.0 | 830 | 20.0 | UA | 1714 | N24211 | LGA | IAH | 227.0 | 1416 | 5 | 29 | 2013-01-01T10:00:00Z |
2 | 2013 | 1 | 1 | 542.0 | 540 | 2.0 | 923.0 | 850 | 33.0 | AA | 1141 | N619AA | JFK | MIA | 160.0 | 1089 | 5 | 40 | 2013-01-01T10:00:00Z |
3 | 2013 | 1 | 1 | 544.0 | 545 | -1.0 | 1004.0 | 1022 | -18.0 | B6 | 725 | N804JB | JFK | BQN | 183.0 | 1576 | 5 | 45 | 2013-01-01T10:00:00Z |
4 | 2013 | 1 | 1 | 554.0 | 600 | -6.0 | 812.0 | 837 | -25.0 | DL | 461 | N668DN | LGA | ATL | 116.0 | 762 | 6 | 0 | 2013-01-01T11:00:00Z |
flights2 = flights.assign(
cancelled=lambda x: pd.isna(x["dep_time"]),
sched_hour=lambda x: x["sched_dep_time"] // 100,
sched_min=lambda x: x["sched_dep_time"] % 100,
sched_dep_time=lambda x: x["sched_hour"] + x["sched_min"] / 60,
)
(
ggplot(flights2, aes(x="sched_dep_time"))
+ geom_freqpoly(aes(color="cancelled"), binwidth=1 / 4)
)
However this plot isn’t great because there are many more non-cancelled flights than cancelled flights. In the next section we’ll explore some techniques for improving this comparison.
13.4.1. Exercises#
What happens to missing values in a histogram? What happens to missing values in a bar chart? Why is there a difference in how missing values are handled in histograms and bar charts?
Recreate the frequency plot of
scheduled_dep_time
coloured by whether the flight was cancelled or not. Also facet by thecancelled
variable. Experiment with different values of thescales
variable in the faceting function to mitigate the effect of more non-cancelled flights than cancelled flights.
13.5. Covariation#
If variation describes the behavior within a variable, covariation describes the behavior between variables. Covariation is the tendency for the values of two or more variables to vary together in a related way. The best way to spot covariation is to visualise the relationship between two or more variables, but note that covariation doesn’t imply a causal relationship between variables.
13.5.1. A categorical and a numerical variable#
For example, let’s explore how the price of a diamond varies with its quality (measured by "cut"
) using geom_freqpoly()
:
(
ggplot(diamonds, aes(x="price"))
+ geom_freqpoly(aes(color="cut"), binwidth=500, linewidth=0.75)
)
The default appearance of geom_freqpoly()
is not that useful here because the height, determined by the overall count, differs so much across cuts, making it hard to see the differences in the shapes of their distributions.
To make the comparison easier we need to swap what is displayed on the y-axis. Instead of displaying count, we’ll display the density, which is the count standardised so that the area under each frequency polygon is one.
(
ggplot(diamonds, aes(x="price"))
+ geom_density(aes(color="cut", fill="cut"), size=1, alpha=0.2)
)
There’s something rather surprising about this plot - it appears that fair diamonds (the lowest quality) have the highest average price! But maybe that’s because density plots are a little hard to interpret - there’s a lot going on in this plot.
A visually simpler plot for exploring this relationship is using side-by-side boxplots.
(ggplot(diamonds, aes(x="cut", y="price")) + geom_boxplot())
We see much less information about the distribution, but the boxplots are much more compact so we can more easily compare them (and fit more on one plot). It supports the counter-intuitive finding that better quality diamonds are typically cheaper! In the exercises, you’ll be challenged to figure out why.
"cut"
is an ordered categorical variable: fair is worse than good, which is worse than very good and so on. Many categorical variables don’t have such an intrinsic order, so you might want to reorder them to make a more informative display. One way to do that is according to the median value, though other options are available.
As an example, with the mpg dataset, we might want to look at how highway mileage varies across classes:
mpg = pd.read_csv(
"https://vincentarelbundock.github.io/Rdatasets/csv/ggplot2/mpg.csv", index_col=0
)
mpg["class"] = mpg["class"].astype("category")
(ggplot(mpg, aes(x="class", y="hwy")) + geom_boxplot())
To make the trend easier to see, we can reorder class based on the median value of "hwy"
:
(ggplot(mpg) + geom_boxplot(aes(as_discrete("class", order_by="..middle.."), "hwy")))
If you have long variable names, geom_boxplot() will work better if you flip it 90°. You can do that by adding coord_flip()
.
(
ggplot(mpg)
+ geom_boxplot(aes(as_discrete("class", order_by="..middle.."), "hwy"))
+ coord_flip()
)
13.5.1.1. Exercises#
Use what you’ve learned to improve the visualisation of the departure times of cancelled vs. non-cancelled flights.
Based on EDA, what variable in the diamonds dataset appears to be most important for predicting the price of a diamond? How is that variable correlated with cut? Why does the combination of those two relationships lead to lower quality diamonds being more expensive?
Create a visualisation of diamond prices vs. a categorical variable from the
diamonds
dataset usinggeom_violin()
, then a facetedgeom_histogram()
, then a colouredgeom_freqpoly()
, and then a colouredgeom_density()
. Compare and contrast the four plots. What are the pros and cons of each method of visualising the distribution of a numerical variable based on the levels of a categorical variable?If you have a small dataset, it’s sometimes useful to use
geom_jitter()
to avoid overplotting to more easily see the relationship between a continuous and categorical variable. The ggbeeswarm package provides a number of methods similar togeom_jitter()
. List them and briefly describe what each one does.
13.5.2. Two categorical variables#
To visualise the covariation between categorical variables, you’ll need to count the number of observations for each combination of levels of these categorical variables. You can do this with a pd.crosstab()
that we then melt to put it in “tidy” format.
ct_cut_color = pd.melt(
pd.crosstab(diamonds["cut"], diamonds["color"]).reset_index(),
id_vars=["cut"],
value_vars=diamonds["color"].unique(),
)
Followed by visualising it with geom_tile()
:
(ggplot(ct_cut_color, aes(x="color", y="cut")) + geom_tile(aes(fill="value")))
13.5.3. Exercises#
How could you rescale the count dataset above to more clearly show the distribution of cut within color, or colour within cut?
What different data insights do you get with a segmented bar chart if colour is mapped to the
x
aesthetic and cut is mapped to the fill aesthetic? Calculate the counts that fall into each of the segments.Use
geom_tile()
together with pandas to explore how average flight departure delays vary by destination and month of year. What makes the plot difficult to read? How could you improve it?
13.5.4. Two numerical variables#
You’ve already seen one great way to visualise the covariation between two numerical variables: draw a scatterplot with geom_point()
.
You can see covariation as a pattern in the points.
For example, you can see a positive association between the carat size and price of a diamond: diamonds with more carats have a higher price.
The relationship is exponential.
(ggplot(smaller_diamonds, aes(x="carat", y="price")) + geom_point())
(In this section we’ll use the smaller_diamonds
dataset to stay focused on the bulk of the diamonds that are smaller than 3 carats)
Scatterplots become less useful as the size of your dataset grows, because points begin to overplot, and pile up into areas of uniform black, making it hard to judge differences in the density of the data across the 2-dimensional space as well as making it hard to spot the trend.
You’ve already seen one way to fix the problem: using the alpha
aesthetic to add transparency.
(ggplot(smaller_diamonds, aes(x="carat", y="price")) + geom_point(alpha=1 / 20))
But using transparency can be challenging for very large datasets. In that case, we recommend a binscatter, or binned scatterplot. A binned scatterplot divides the conditioning variable, "carat"
in our example, into equally sized bins or quantiles, and then plots the conditional mean of the dependent variable, "price"
in our example, within each bin. Bin scatters often come with confidence intervals too. A good bin scatter package in Python is binsreg. However, bin scatters are an advanced topic, and we won’t cover them here.
13.6. pandas built-in tools for EDA#
pandas has some great options for built-in EDA; in fact we’ve already seen one of them, df.info()
which, as well as reporting datatypes and memory usage, also tells us how many observations in each column are ‘truthy’ rather than ‘falsy’, ie how many have non-null values.
13.6.1. Exploratory tables and descriptive statistics#
A small step beyond .info()
to get tables is to use .describe()
which, if you have mixed datatypes that include floats, will report some basic summary statistics:
diamonds.describe()
carat | depth | table | price | x | y | z | |
---|---|---|---|---|---|---|---|
count | 53940.000000 | 53940.000000 | 53940.000000 | 53940.000000 | 53940.000000 | 53940.000000 | 53940.000000 |
mean | 0.797940 | 61.749405 | 57.457184 | 3932.799722 | 5.731157 | 5.734526 | 3.538734 |
std | 0.474011 | 1.432621 | 2.234491 | 3989.439738 | 1.121761 | 1.142135 | 0.705699 |
min | 0.200000 | 43.000000 | 43.000000 | 326.000000 | 0.000000 | 0.000000 | 0.000000 |
25% | 0.400000 | 61.000000 | 56.000000 | 950.000000 | 4.710000 | 4.720000 | 2.910000 |
50% | 0.700000 | 61.800000 | 57.000000 | 2401.000000 | 5.700000 | 5.710000 | 3.530000 |
75% | 1.040000 | 62.500000 | 59.000000 | 5324.250000 | 6.540000 | 6.540000 | 4.040000 |
max | 5.010000 | 79.000000 | 95.000000 | 18823.000000 | 10.740000 | 58.900000 | 31.800000 |
Although helpful, that sure is hard to read! We can improve this by using the round()
method too:
sum_table = diamonds.describe().round(1)
sum_table
carat | depth | table | price | x | y | z | |
---|---|---|---|---|---|---|---|
count | 53940.0 | 53940.0 | 53940.0 | 53940.0 | 53940.0 | 53940.0 | 53940.0 |
mean | 0.8 | 61.7 | 57.5 | 3932.8 | 5.7 | 5.7 | 3.5 |
std | 0.5 | 1.4 | 2.2 | 3989.4 | 1.1 | 1.1 | 0.7 |
min | 0.2 | 43.0 | 43.0 | 326.0 | 0.0 | 0.0 | 0.0 |
25% | 0.4 | 61.0 | 56.0 | 950.0 | 4.7 | 4.7 | 2.9 |
50% | 0.7 | 61.8 | 57.0 | 2401.0 | 5.7 | 5.7 | 3.5 |
75% | 1.0 | 62.5 | 59.0 | 5324.2 | 6.5 | 6.5 | 4.0 |
max | 5.0 | 79.0 | 95.0 | 18823.0 | 10.7 | 58.9 | 31.8 |
Published summary statistics tables often list one variable per row, and if your data frame has many variables, describe()
can quickly get too wide to read easily. You can transpose it using the T
property (or the transpose()
method):
sum_table = sum_table.T
sum_table
count | mean | std | min | 25% | 50% | 75% | max | |
---|---|---|---|---|---|---|---|---|
carat | 53940.0 | 0.8 | 0.5 | 0.2 | 0.4 | 0.7 | 1.0 | 5.0 |
depth | 53940.0 | 61.7 | 1.4 | 43.0 | 61.0 | 61.8 | 62.5 | 79.0 |
table | 53940.0 | 57.5 | 2.2 | 43.0 | 56.0 | 57.0 | 59.0 | 95.0 |
price | 53940.0 | 3932.8 | 3989.4 | 326.0 | 950.0 | 2401.0 | 5324.2 | 18823.0 |
x | 53940.0 | 5.7 | 1.1 | 0.0 | 4.7 | 5.7 | 6.5 | 10.7 |
y | 53940.0 | 5.7 | 1.1 | 0.0 | 4.7 | 5.7 | 6.5 | 58.9 |
z | 53940.0 | 3.5 | 0.7 | 0.0 | 2.9 | 3.5 | 4.0 | 31.8 |
Of course, the stats provided in this pre-built table are not very customised. So what do we do to get the table that we actually want? Well, the answer is to draw on the contents of the previous data chapters, particularly the introduction to data analysis. Groupbys, merges, aggregations: use all of them to produce the EDA table that you want.
If you’re exploring data, you might also want to be able to read everything clearly and see any deviations from what you’d expect quickly. pandas has some built-in functionality that styles data frames to help you. These styles persist when you export the data frame to, say, Excel, too.
Here’s an example that highlights some ways of styling data frames, making use of several features such as: unstacking into a wider format (unstack
), changing the units (lambda
function; note that 1e3
is shorthand for 1000
on computers), fill NaNs with unobtrusive strings (.fillna('-')
), removing numbers after the decimal place (.style.format(precision=0)
), and adding a caption (.style.set_caption
).
(
diamonds.groupby(["cut", "color"])["price"]
.mean()
.unstack()
.apply(lambda x: x / 1e3)
.fillna("-")
.style.format(precision=2)
.set_caption("Sale price (thousands)")
)
color | D | E | F | G | H | I | J |
---|---|---|---|---|---|---|---|
cut | |||||||
Fair | 4.29 | 3.68 | 3.83 | 4.24 | 5.14 | 4.69 | 4.98 |
Good | 3.41 | 3.42 | 3.50 | 4.12 | 4.28 | 5.08 | 4.57 |
Very Good | 3.47 | 3.21 | 3.78 | 3.87 | 4.54 | 5.26 | 5.10 |
Premium | 3.63 | 3.54 | 4.32 | 4.50 | 5.22 | 5.95 | 6.29 |
Ideal | 2.63 | 2.60 | 3.37 | 3.72 | 3.89 | 4.45 | 4.92 |
Although a neater one than we’ve seen, this is still a drab table of numbers. The eye is not immediately drawn to it!
To remedy that, let’s take a look at another styling technique: the use of colour. Let’s say we wanted to make a table that showed a cross-tabulation between cut and color; that is the counts of objects appearing in both of these fields according to the categories.
To perform a cross-tabulation, we’ll use the built-in pd.crosstab()
but we’ll ask that the values that appear in the table (counts) be lit up with a heatmap using style.background_gradient()
too:
pd.crosstab(diamonds["color"], diamonds["cut"]).style.background_gradient(cmap="plasma")
cut | Fair | Good | Very Good | Premium | Ideal |
---|---|---|---|---|---|
color | |||||
D | 163 | 662 | 1513 | 1603 | 2834 |
E | 224 | 933 | 2400 | 2337 | 3903 |
F | 312 | 909 | 2164 | 2331 | 3826 |
G | 314 | 871 | 2299 | 2924 | 4884 |
H | 303 | 702 | 1824 | 2360 | 3115 |
I | 175 | 522 | 1204 | 1428 | 2093 |
J | 119 | 307 | 678 | 808 | 896 |
By default, background_gradient()
highlights each number relative to the others in its column; you can highlight by row using axis=1
or relative to all table values using axis=0
. And of course plasma
is just one of many available colormaps!
Exercise
Do a new cross-tabulation using a different colourmap.
Here are a couple of other styling tips for data frames.
First, use bars to show ordering:
(
pd.crosstab(diamonds["color"], diamonds["cut"])
.style.format(precision=0)
.bar(color="#d65f5f")
)
cut | Fair | Good | Very Good | Premium | Ideal |
---|---|---|---|---|---|
color | |||||
D | 163 | 662 | 1513 | 1603 | 2834 |
E | 224 | 933 | 2400 | 2337 | 3903 |
F | 312 | 909 | 2164 | 2331 | 3826 |
G | 314 | 871 | 2299 | 2924 | 4884 |
H | 303 | 702 | 1824 | 2360 | 3115 |
I | 175 | 522 | 1204 | 1428 | 2093 |
J | 119 | 307 | 678 | 808 | 896 |
Use .hightlight_max()
, and similar commands, to show important entries:
pd.crosstab(diamonds["color"], diamonds["cut"]).style.highlight_max().format("{:.0f}")
cut | Fair | Good | Very Good | Premium | Ideal |
---|---|---|---|---|---|
color | |||||
D | 163 | 662 | 1513 | 1603 | 2834 |
E | 224 | 933 | 2400 | 2337 | 3903 |
F | 312 | 909 | 2164 | 2331 | 3826 |
G | 314 | 871 | 2299 | 2924 | 4884 |
H | 303 | 702 | 1824 | 2360 | 3115 |
I | 175 | 522 | 1204 | 1428 | 2093 |
J | 119 | 307 | 678 | 808 | 896 |
You can find a full set of styling commands here.
13.6.2. Exploratory Plotting with pandas#
pandas has some built-in plotting options to help you look at data quickly. These can be accessed via .plot.*
or .plot()
, depending on the context. Let’s make a quick .plot()
using a dataset on taxis.
taxis = pd.read_csv("https://github.com/mwaskom/seaborn-data/raw/master/taxis.csv")
# turn the pickup time column into a datetime
taxis["pickup"] = pd.to_datetime(taxis["pickup"])
# set some other columns types
taxis = taxis.astype(
{
"dropoff": "datetime64[ns]",
"pickup": "datetime64[ns]",
"color": "category",
"payment": "category",
"pickup_zone": "string",
"dropoff_zone": "string",
"pickup_borough": "category",
"dropoff_borough": "category",
}
)
taxis.head()
pickup | dropoff | passengers | distance | fare | tip | tolls | total | color | payment | pickup_zone | dropoff_zone | pickup_borough | dropoff_borough | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 2019-03-23 20:21:09 | 2019-03-23 20:27:24 | 1 | 1.60 | 7.0 | 2.15 | 0.0 | 12.95 | yellow | credit card | Lenox Hill West | UN/Turtle Bay South | Manhattan | Manhattan |
1 | 2019-03-04 16:11:55 | 2019-03-04 16:19:00 | 1 | 0.79 | 5.0 | 0.00 | 0.0 | 9.30 | yellow | cash | Upper West Side South | Upper West Side South | Manhattan | Manhattan |
2 | 2019-03-27 17:53:01 | 2019-03-27 18:00:25 | 1 | 1.37 | 7.5 | 2.36 | 0.0 | 14.16 | yellow | credit card | Alphabet City | West Village | Manhattan | Manhattan |
3 | 2019-03-10 01:23:59 | 2019-03-10 01:49:51 | 1 | 7.70 | 27.0 | 6.15 | 0.0 | 36.95 | yellow | credit card | Hudson Sq | Yorkville West | Manhattan | Manhattan |
4 | 2019-03-30 13:27:42 | 2019-03-30 13:37:14 | 3 | 2.16 | 9.0 | 1.10 | 0.0 | 13.40 | yellow | credit card | Midtown East | Yorkville West | Manhattan | Manhattan |
taxis.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6433 entries, 0 to 6432
Data columns (total 14 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 pickup 6433 non-null datetime64[ns]
1 dropoff 6433 non-null datetime64[ns]
2 passengers 6433 non-null int64
3 distance 6433 non-null float64
4 fare 6433 non-null float64
5 tip 6433 non-null float64
6 tolls 6433 non-null float64
7 total 6433 non-null float64
8 color 6433 non-null category
9 payment 6389 non-null category
10 pickup_zone 6407 non-null string
11 dropoff_zone 6388 non-null string
12 pickup_borough 6407 non-null category
13 dropoff_borough 6388 non-null category
dtypes: category(4), datetime64[ns](2), float64(5), int64(1), string(2)
memory usage: 528.5 KB
(
taxis.set_index("pickup")
.groupby(pd.Grouper(freq="D"))["total"]
.mean()
.plot(
title="Mean taxi fares",
xlabel="",
ylabel="Fare (USD)",
)
);
Again, if you can get the data in the right shape, you can plot it. The same function works with multiple lines
(
taxis.set_index("pickup")
.groupby(pd.Grouper(freq="D"))[["fare", "tip", "tolls"]]
.mean()
.plot(
style=["-", ":", "-."],
title="Components of taxi fares",
xlabel="",
ylabel="USD",
)
);
Now let’s see some of the other quick .plot.*
options.
A bar chart (use barh
for horizontal orientation; rot
sets rotation of labels):
taxis.value_counts("payment").sort_index().plot.bar(title="Counts", rot=0);
This next one, uses .plot.hist()
to create a histogram.
taxis["tip"].plot.hist(bins=30, title="Tip");
Boxplot:
(taxis[["fare", "tolls", "tip"]].plot.box());
Scatter plot:
taxis.plot.scatter(x="fare", y="tip", alpha=0.7, ylim=(0, None));
13.7. Other tools for EDA#
Between pandas and visualisation packages, you have a lot of what you need for EDA. But there are some tools just dedicated to making EDA easier that it’s worth knowing about.
13.7.1. skimpy for summary statistics#
The skimpy package is a light weight tool that provides summary statistics about variables in data frames in the console (rather than in a big HTML report, which is what the other EDA packages in the rest of this chapter too). Sometimes running .summary()
on a data frame isn’t enough, and skimpy fills this gap. It also comes with the clean_columns()
function for cleaning column names that we saw in an earlier chapter. To install skimpy, run pip install skimpy
in the terminal.
Let’s see skimpy in action.
skim(taxis)
╭──────────────────────────────────────────────── skimpy summary ─────────────────────────────────────────────────╮ │ Data Summary Data Types Categories │ │ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ ┏━━━━━━━━━━━━━━━━━━━━━━━┓ │ │ ┃ dataframe ┃ Values ┃ ┃ Column Type ┃ Count ┃ ┃ Categorical Variables ┃ │ │ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ ┡━━━━━━━━━━━━━━━━━━━━━━━┩ │ │ │ Number of rows │ 6433 │ │ float64 │ 5 │ │ color │ │ │ │ Number of columns │ 14 │ │ category │ 4 │ │ payment │ │ │ └───────────────────┴────────┘ │ datetime64 │ 2 │ │ pickup_borough │ │ │ │ string │ 2 │ │ dropoff_borough │ │ │ │ int64 │ 1 │ └───────────────────────┘ │ │ └─────────────┴───────┘ │ │ number │ │ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┓ │ │ ┃ column_name ┃ NA ┃ NA % ┃ mean ┃ sd ┃ p0 ┃ p25 ┃ p50 ┃ p75 ┃ p100 ┃ hist ┃ │ │ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━━┩ │ │ │ passengers │ 0 │ 0 │ 1.5 │ 1.2 │ 0 │ 1 │ 1 │ 2 │ 6 │ ▇▁ ▁ │ │ │ │ distance │ 0 │ 0 │ 3 │ 3.8 │ 0 │ 0.98 │ 1.6 │ 3.2 │ 37 │ ▇▁ │ │ │ │ fare │ 0 │ 0 │ 13 │ 12 │ 1 │ 6.5 │ 9.5 │ 15 │ 150 │ ▇▁ │ │ │ │ tip │ 0 │ 0 │ 2 │ 2.4 │ 0 │ 0 │ 1.7 │ 2.8 │ 33 │ ▇ │ │ │ │ tolls │ 0 │ 0 │ 0.33 │ 1.4 │ 0 │ 0 │ 0 │ 0 │ 24 │ ▇ │ │ │ │ total │ 0 │ 0 │ 19 │ 14 │ 1.3 │ 11 │ 14 │ 20 │ 170 │ ▇▁ │ │ │ └───────────────────┴──────┴─────────┴─────────┴───────┴───────┴─────────┴───────┴───────┴────────┴──────────┘ │ │ category │ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┓ │ │ ┃ column_name ┃ NA ┃ NA % ┃ ordered ┃ unique ┃ │ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━┩ │ │ │ color │ 0 │ 0 │ False │ 2 │ │ │ │ payment │ 44 │ 0.68 │ False │ 3 │ │ │ │ pickup_borough │ 26 │ 0.4 │ False │ 5 │ │ │ │ dropoff_borough │ 45 │ 0.7 │ False │ 6 │ │ │ └─────────────────────────────────────────┴──────────┴──────────────┴─────────────────────┴──────────────────┘ │ │ datetime │ │ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │ │ ┃ column_name ┃ NA ┃ NA % ┃ first ┃ last ┃ frequency ┃ │ │ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │ │ │ pickup │ 0 │ 0 │ 2019-02-28 23:29:03 │ 2019-03-31 23:43:45 │ None │ │ │ │ dropoff │ 0 │ 0 │ 2019-02-28 23:32:35 │ 2019-04-01 00:13:58 │ None │ │ │ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │ │ string │ │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │ │ ┃ column_name ┃ NA ┃ NA % ┃ words per row ┃ total words ┃ │ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ │ │ pickup_zone │ 26 │ 0.4 │ 2.5 │ 15791 │ │ │ │ dropoff_zone │ 45 │ 0.7 │ 2.5 │ 15851 │ │ │ └────────────────────────────┴────────┴────────────┴──────────────────────────────┴──────────────────────────┘ │ ╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯
13.8. Summary#
In this chapter, you’ve learned a variety of tools to help you understand the variation within your data. You’ve seen techniques that work with a single variable at a time and with a pair of variables. This might seem painfully restrictive if you have tens or hundreds of variables in your data, but they’re foundation upon which all other techniques are built.
In the next chapter, we’ll focus on the tools we can use to communicate our results.