By the end of this chapter, you will be able to:
In this chapter, we will cover the basics of data analytics and statistics. You will also learn how to identify outliers and gain an understanding of the relationship between variables.
Data has fundamentally transformed the 21st century. Thanks to easy access to computers, companies and organizations have been able to change the way they work with larger and more complex datasets. Using data, insights that would have been virtually impossible to find 50 years ago can now be found with just a few lines of computer code. In this chapter, we will discuss what data is and how data analysis can be used to unlock insights and recognize patterns.
Let's start with the first question: what is data? Data (the plural of the word datum) can be thought of as recorded measurements of something in the real world. For example, a list of heights is data – that is, height is a measure of the distance between a person's head and their feet. We usually call that something the data is describing a unit of observation. In the case of these heights, a person is the unit of observation.
As you can imagine, there is a lot of data that we can gather to describe a person – including their age, weight, whether they are a smoker, and more. One or more of these measurements used to describe one specific unit of observation is called a data point, and each measurement in a data point is called a variable (this is also often referred to as a feature). When you have several data points together, you have a dataset.
Data can also be broken down into two main categories: quantitative and qualitative:
Quantitative data is a measurement that can be described as a number; qualitative data is data that is described by non-numerical values, such as text. Your height is data that would be described as quantitative. However, describing yourself as either a "smoker" or a "non-smoker" would be considered qualitative data.
Quantitative data can be further classified into two subcategories: discrete and continuous. Discrete quantitative values are values that can take on a fixed level of precision – usually integers. For example, the number of surgeries you have had in your life is a discrete value – you can have 0, 1, or more surgeries, but you cannot have 1.5 surgeries. A continuous variable is a value that, in theory, could be divided with an arbitrary amount of precision. For example, your body mass could be described with arbitrary precision to be 55, 55.3, 55.32, and so on. In practice, of course, measuring instruments limit our precision. However, if a value could be described with higher precision, then it is generally considered continuous.
Qualitative data can generally be converted into quantitative data, and quantitative data can also be converted into qualitative data. This is explained later in the chapter using an example.
Let's think about this using the example of being a "smoker" versus a "non-smoker". While you can describe yourself to be in the category of "smoker" or "non-smoker", you could also reimagine these categories as answers to the statement "you smoke regularly", and then use the Boolean values of 0 and 1 to represent "true" and "false," respectively.
Similarly, in the opposite direction, quantitative data, such as height, can be converted into qualitative data. For example, instead of thinking of an adult's height as a number in inches or centimeters (cm), you can classify them into groups, with people greater than 72 inches (that is, 183 cm) in the category "tall," people between 63 inches and 72 inches (that is, between 160 and 183 cm) as "medium," and people shorter than 63 inches (that is, 152 cm) as "short."
Raw data, by itself, is simply a group of values. However, it is not very interesting in this form. It is only when we start to find patterns in the data and begin to interpret them that we can start to do interesting things such as make predictions about the future and identify unexpected changes. These patterns in the data are referred to as information. Eventually, a large organized collection of persistent and extensive information and experience that can be used to describe and predict phenomena in the real world is called knowledge. Data analysis is the process by which we convert data into information and, thereafter, knowledge. When data analysis is combined with making predictions, we then have data analytics.
There are a lot of tools that are available to make sense of data. One of the most powerful tools in the toolbox of data analysis is using mathematics on datasets. One of these mathematical tools is statistics.
Statistics can be further divided into two subcategories: descriptive statistics and inferential statistics.
Descriptive statistics are used to describe data. Descriptive statistics on a single variable in a dataset are referred to as univariate analysis, while descriptive statistics that look at two or more variables at the same time are referred to as multivariate analysis.
In contrast, inferential statistics think of datasets as a sample, or a small portion of measurements from a larger group called a population. For example, a survey of 10,000 voters in a national election is a sample of the entire population of voters in a country. Inferential statistics are used to try to infer the properties of a population, based on the properties of a sample.
In this book, we will primarily be focusing on descriptive statistics. For more information on inferential statistics, please refer to a statistics textbook, such as Statistics, by David Freedman, Robert Pisani, and Roger Purves.
Example:
Imagine that you are a health policy analyst and are given the following dataset with information about patients:
When given a dataset, it's often helpful to classify the underlying data. In this case, the unit of observation for the dataset is an individual patient, because each row represents an individual observation, which is a unique patient. There are 10 data points, each with 5 variables. Three of the columns, Year of Birth, Height, and Number of Doctor Visits, are quantitative because they are represented by numbers. Two of the columns, Eye Color and Country of Birth, are qualitative.
In this activity, we will classify the data in a dataset. You are about to start a job in a new city at an up-and-coming start-up. You're excited to start your new job, but you've decided to sell all your belongings before you head off. This includes your car. You're not sure at what price to sell it for, so you decide to collect some data. You ask some friends and family who recently sold their cars what the make of the car was, and how much they sold the cars for. Based on this information, you now have a dataset.
The data is as follows:
Steps to follow:
The solution for this activity can be found via this link.
As previously mentioned, descriptive statistics is one of the ways in which we can analyze data in order to understand it. Both univariate and multivariate analysis can give us an insight into what might be going on with a phenomenon. In this section, we will take a closer look at the basic mathematical techniques that we can use to better understand and describe a dataset.
As previously mentioned, one of the main branches of statistics is univariate analysis. These methods are used to understand a single variable in a dataset. In this section, we will look at some of the most common univariate analysis techniques.
The distribution of data is simply a count of the number of values that are in a dataset. For example, let's say that we have a dataset of 1,000 medical records, and one of the variables in the dataset is eye color. If we look at the dataset and find that 700 people have brown eyes, 200 people have green eyes, and 100 people have blue eyes, then we have just described the distribution of the dataset. Specifically, we have described the absolute frequency distribution. If we were to describe the counts not by the actual number of occurrences in the dataset, but as the proportion of the total number of data points, then we are describing its relative frequency distribution. In the preceding eye color example, the relative frequency distribution would be 70% brown eyes, 20% green eyes, and 10% blue eyes.
It's easy to calculate a distribution when the variable can take on a small number of fixed values such as eye color. But what about a quantitative variable that can take on many different values, such as height? The general way to calculate distributions for these types of variables is to make interval "buckets" that these values can be assigned to and then calculate distributions using these buckets. For example, height can be broken down into 5-cm interval buckets to make the following absolute distribution (please refer to Figure 1.6). We can then divide each row in the table by the total number of data points (that is, 10,000) and get the relative distribution.
Another useful thing to do with distributions is to graph them. We will now create a histogram, which is a graphical representation of the continuous distribution using interval buckets.
In this exercise, we will use Microsoft Excel to create a histogram. Imagine, as a healthcare policy analyst, that you want to see the distribution of heights to note any patterns. To accomplish this task, we need to create a histogram.
We can use spreadsheet software such as Excel, Python, or R to create histograms. For convenience, we will use Excel. Also, all the datasets used in this chapter, can be found on GitHub: https://github.com/TrainingByPackt/SQL-for-Data-Analytics/tree/master/Datasets.
Perform the following steps:
heights.csv
dataset file in the Datasets
folder of the GitHub repository. After navigating to it, click on OK.Looking at the shape of the distribution can help you to find interesting patterns. Notice here the symmetric bell-shaped curl of this distribution. This distribution is often found in many datasets and is known as the normal distribution. This book won't go into too much detail about this distribution but keep an eye out for it in your data analysis – it shows up quite often.
Quantiles
One way to quantify data distribution numerically is to use quantiles. N-quantiles are a set of n-1 points used to divide a variable into n groups. These points are often called cut points. For example, a 4-quantile (also referred to as quartiles) is a group of three points that divide a variable into four, approximately equal groups of numbers. There are several common names for quantiles that are used interchangeably, and these are as follows:
The procedure for calculating quantiles actually varies from place to place. We will use the following procedure to calculate the n-quantiles for d data points for a single variable:
These steps are a little complicated to understand by themselves, so let's work through an exercise. With most modern tools, including SQL, computers can quickly calculate quantiles with built-in functionality.
Before you start your new job, your new boss wants you to look at some data before you start on Monday, so that you have a better sense of one of the problems you will be working on – that is, the increasing sales of add-ons and upgrades for car purchases. Your boss sends over a list of 11 car purchases and how much they have spent on add-ons and upgrades to the base model of the new ZoomZoom Model Chi. In this exercise, we will classify the data and calculate the quartiles for the car purchase using Excel. The following are the values of Add-on Sales ($): 5,000, 1,700, 8,200, 1,500, 3,300, 9,000, 2,000, 0, 0, 2,300, and 4,700.
All the datasets used in this chapter, can be found on GitHub: https://github.com/TrainingByPackt/SQL-for-Data-Analytics/tree/master/Datasets.
Perform the following steps to complete the exercise:
auto_upgrades.csv
dataset file in the Datasets
folder of the GitHub repository. Navigate to the file and click on OK.In this exercise, we learned how to classify the data and calculate the quartiles using Excel.
One of the common questions asked of a variable in a dataset is what a typical value for that variable is. This value is often described as the central tendency of the variable. There are many numbers calculated from a dataset that are often used to describe its central tendency, each with their own advantages and disadvantages. Some of the ways to measure central tendency include the following:
While the median is a bit unwieldy to calculate, it is less affected by outliers, unlike mean. To illustrate this fact, we will calculate the median of the skewed age dataset of 26, 25, 31, 35, 29, and 82. This time, when we calculate the median of the dataset, we get the value of 30. This value is much closer to the typical value of the dataset than the average of 38. This robustness toward outliers is one of the major 'reasons why a median is calculated.
As a general rule, it is a good idea to calculate both the mean and median of a variable. If there is a significant difference in the value of the mean and the median, then the dataset may have outliers.
In this exercise, we will calculate the central tendency of the given data. To better understand the Add-on Sales data, you will need to gain an understanding of what the typical value for this variable is. We will calculate the mode, mean, and median of the Add-on Sales data. Here is the data for the 11 cars purchased: 5,000, 1,700, 8,200, 1,500, 3,300, 9,000, 2,000, 0, 0, 2,300, and 4,700.
Perform the following steps to implement the exercise:
Determine the middle value. Because there are 11 values, the middle value will be sixth in the list. We now take the sixth element in the ordered data and get a median of 2,300.
When we compare the mean and the median, we see that there is a significant difference between the two. As previously mentioned, it is a sign that we have outliers in our dataset. We will discuss in future sections how to determine which values are outliers.
Another property that is of interest in a dataset is discovering how close together data points are in a variable. For example, the number sets [100, 100, 100] and [50, 100, 150] both have a mean of 100, but the numbers in the second group are spread out more than the first. This property of describing how the data is spread is called dispersion.
There are many ways to measure the dispersion of a variable. Here are some of the most common ways to evaluate dispersion:
One subtle distinction to note is that there are two different formulas for standard deviation, which are shown in Figure 1.14. When the dataset represents the entire population, you should calculate the population standard deviation using formula A in Figure 1.14. If your sample represents a portion of the observations, then you should use formula B for the sample standard deviation, as displayed in Figure 1.14. When in doubt, use the sample variance, as it is considered more conservative. Also, in practice, the difference between the two formulas is very small when there are many data points.
The standard deviation is generally the quantity used most often to describe dispersion. However, like range, it can also be affected by outliers, though not as extremely as the range is. It can also be fairly involved to calculate. Modern tools, however, usually make it very easy to calculate the standard deviation.
One final note is that, occasionally, you may see a related value, variance, listed as well. This quantity is simply the square of the standard deviation:
For more information on calculating quantiles and quartiles, refer to the Data Distribution section in this chapter.
IQR, unlike range and standard deviation, is robust toward outliers, and so, while it is the most complicated of the functions to calculate, it provides a more robust way to measure the spread of datasets. In fact, IQR is often used to define outliers. If a value in a dataset is smaller than Q1 - 1.5 X IQR, or larger than Q3 + 1.5 X IQR, then the value is considered an outlier.
To better understand the sales of additions and upgrades, you need to take a closer look at the dispersion of the data. In this exercise, we will calculate the range, standard deviation, IQR, and outliers of Add-on Sales. Here is the data for the 11 cars purchased: 5,000, 1,700, 8,200, 1,500, 3,300, 9,000, 2,000, 0, 0, 2,300, and 4,700.
Follow these steps to perform the exercise:
So far, we have talked about methods for describing a single variable. Now, we will discuss how to find patterns with two variables using bivariate analysis.
A general principle you will find in analytics is that graphs are incredibly helpful in finding patterns. Just as histograms can help you to understand a single variable, scatterplots can help you to understand two variables. Scatterplots can be produced pretty easily using your favorite spreadsheet.
Scatterplots are particularly helpful when there are only a small number of points, usually some number between 30 and 500. If you have a large number of points and plotting them appears to produce a giant blob in your scatterplot, take a random sample of 200 of those points and then plot them to help discern any interesting trends.
A lot of different patterns are worth looking out for within a scatterplot. The most common pattern people look for is an upward or downward trend between the two variables; that is, as one variable increases, does the other variable decrease? Such a trend indicates that there may be a predictable mathematical relationship between the two variables. Figure 1.16 shows an example of a linear trend:
There are also many trends that are worth looking out for that are not linear, including quadratic, exponential, inverse, and logistic. The following diagram shows some of these trends and what they look like:
The process of approximating a trend with a mathematical function is known as regression analysis. Regression analysis plays a critical part in analytics but is outside the scope of this book. For more information on regression analysis, refer to an advanced text, such as Regression Modeling Strategies: With Applications to Linear Models, Logistic Regression, and Survival Analysis by Frank E. Harrell Jr.
While trends are useful for understanding and predicting patterns, detecting changes in trends are often more important. Changes in trends usually indicate a critical change in whatever you are measuring and are worth examining further for an explanation. The following diagram shows an example of a change in a trend, where the linear trend wears off after x=40:
Another pattern people tend to look for is periodicity, that is, repeating patterns in the data. Such patterns can indicate that two variables may have cyclical behavior and can be useful in making predictions. The following diagram shows an example of periodic behavior:
Another use of scatterplots is to help detect outliers. When most points in a graph appear to be in a specific region of the graph, but some points are quite far removed, this may indicate that those points are outliers with regard to the two variables. When performing further bivariate analysis, it may be wise to remove these points in order to reduce noise and produce better insights. The following diagram shows a case of points that may be considered outliers:
These techniques with scatterplots allow data professionals to understand the broader trends in their data and take the first steps to turn data into information.
Pearson Correlation Coefficient
One of the most common trends in analyzing bivariate data is linear trends. Often times though, some linear trends are weak, while other linear trends are strong in how well a linear trend fits the data. In Figure 1.21 and Figure 1.22, we see examples of scatterplots with their line of best fit. This is a line calculated using a technique known as Ordinary Least Square (OLS) regression. Although OLS is beyond the scope of this book, understanding how well bivariate data fits a linear trend is an extraordinarily valuable tool for understanding the relationship between two variables:
The following diagram shows a scatterplot with a weak linear trend:
For more information on OLS regression, please refer to a statistics textbook, such as Statistics by David Freedman, Robert Pisani, and Roger Purves.
One method for quantifying linear correlation is to use what is called the Pearson correlation coefficient. The Pearson correlation coefficient, often represented by the letter r, is a number ranging from -1 to 1, indicating how well a scatterplot fits a linear trend. To calculate the Pearson correlation coefficient, r, we use the following formula:
This formula is a bit heavy, so let's work through an example to turn the formula into specific steps.
Let's calculate the Pearson correlation coefficient for the relationship between Hours Worked Per Week and Sales Per Week ($). In the following diagram, we have listed some data for 10 salesmen at a ZoomZoom dealership in Houston, and how much they netted in sales that week:
Perform the following steps to complete the exercise:
There does not appear to be a strong linear relationship, but there does appear to be a general increase in Sales Per Week ($) versus Hours Worked Per Week.
We learned how to calculate the Pearson correlation coefficient for two variables in this exercise and got the final output as 0.38 after using the formula.
Interpreting and Analyzing the Correlation Coefficient
Calculating the correlation coefficient by hand can be very complicated. It is generally preferable to calculate it on the computer. As you will learn in Chapter 3, SQL for Data Preparation, it is possible to calculate the Pearson correlation coefficient using SQL.
To interpret the Pearson correlation coefficient, compare its value to the table in Figure 1.28. The closer to 0 the coefficient is, the weaker the correlation. The higher the absolute value of a Pearson correlation coefficient, the more likely it is that the points will fit a straight line:
There are a couple of things to watch out for when examining the correlation coefficient. The first thing to watch out for is that the correlation coefficient measures how well two variables fit a linear trend. Two variables may share a strong trend but have a relatively low Pearson correlation coefficient. For example, look at the points in Figure 1.29. If you calculate the correlation coefficient for these two variables, you will find it is -0.08. However, the curve has a very clear quadratic relationship. Therefore, when you look at the correlation coefficients of bivariate data, be on the lookout for non-linear relationships that may describe the relationship between the two variables:
Another point of importance is the number of points used to calculate a correlation. It only takes two points to define a perfectly straight line. Therefore, you may be able to calculate a high correlation coefficient when there are fewer points. However, this correlation coefficient may not hold when more data is presented into the bivariate data. As a rule of thumb, correlation coefficients calculated with fewer than 30 data points should be taken with a pinch of salt. Ideally, you should have as many good data points as you can in order to calculate the correlation.
Notice the use of the term "good data points." One of the recurring themes of this chapter has been the negative impact of outliers on various statistics. Indeed, with bivariate data, outliers can impact the correlation coefficient. Let's take a look at the graph in Figure 1.30. It has 11 points, one of which is an outlier. Due to that outlier, the Pearson correlation coefficient, r, for the data falls to 0.59, but without it, it equals 1.0. Therefore, care should be taken to remove outliers, especially from limited data:
Finally, one of the major problems associated with calculating correlation is the logical fallacy of correlation implying causation. That is, just because x and y have a strong correlation does not mean that x causes y. Let's take our example of the number of hours worked versus the number of sales netted per week. Imagine that, after adding more data points, it turns out that the correlation is 0.5 between these two variables. Many beginner data professionals and experienced executives would conclude that more working hours net more sales and start making their sales team work nonstop. While it is possible that working more hours causes more sales, a high correlation coefficient is not hard evidence for that. Another possibility may even be a reverse set of causation; it is possible that because you produce more sales, there is more paperwork and, therefore, you need to stay longer at the office in order to complete it. In this scenario, working more hours may not cause more sales. Another possibility is that there is a third item responsible for the association between the two variables.
For example, it may actually be that experienced salespeople work longer hours, and experienced salespeople also do a better job of selling. Therefore, the real cause is having employees with lots of sales experience, and the recommendation should be to hire more experienced sales professionals. As analytics professional, you will be responsible for avoiding pitfalls such as correlation and causation, and critically think about all the possibilities that might be responsible for the results you see.
Time Series Data
One of the most important types of bivariate analysis is a time series. A time series is simply a bivariate relationship where the x-axis is time. An example of a time series can be found in Figure 1.31, which shows a time series from January 2010 to late 2012. While, at first glance, this may not seem to be the case, date and time information is quantitative in nature. Understanding how things change over time is one of the most important types of analysis done in organizations and provides a lot of information about the context of the business. All of the patterns discussed in the previous section can also be found in time series data. Time series are also important in organizations because they can be indicative of when specific changes happened. Such time points can be useful in determining what caused these changes:
In this activity, we will explore a dataset in full. It's your first day at ZoomZoom, where the company is hard at work building the world's best electric vehicles and scooters in order to stop climate change. You have been recently hired as the newest senior data analyst for the company. You're incredibly excited to start your job and are ready to help however you can. Your manager, the head of analytics is happy to see you, but unfortunately, can't help you get set up today because of a company emergency (something about the CEO having a meltdown on a podcast). You don't have access to a database, but he did email you a CSV file with some data about national dealerships on it. He wants you to do some high-level analysis on annual sales at dealerships across the country:
dealerships.csv
document in a spreadsheet or text editor. This can be found in the Datasets
folder of the GitHub repository.The solution for this activity can be found via this link.
In all of our examples so far, our datasets have been very clean. However, real-world datasets are almost never this nice. One of the many problems you may have to deal with when working with datasets is missing values. We will discuss the specifics of preparing data further in Chapter 3, SQL for Data Preparation. Nonetheless, in this section, we would like to take some time to discuss some of the strategies you can use to handle missing data. Some of your options include the following:
You will also find that a decent portion of data analysis is more art than science. Working with missing data is one such area. With experience, you will find a combination of strategies that work well for different scenarios.
Another piece of analysis that is useful in data analysis is statistical significance testing. Often times, an analyst is interested in comparing the statistical properties of two groups, or perhaps just one group before and after a change. Of course, the difference between these two groups may just be due to chance.
An example of where this comes up is in marketing A/B tests. Companies will often test two different types of landing pages for a product and measure the click-through rate (CTR). You may find that the CTR for variation A of the landing page is 10%, and the CTR for variation B is 11%. So, does that mean that variation B is 10% better than A, or is this just a result of day-to-day variance? Statistical testing helps us to determine just that.
In statistical testing, there are a couple of major parts you need to have (Figure 1.32). First, we have the test statistic we are examining. It may be a proportion, an average, the difference between two groups, or a distribution. The next necessary part is a null hypothesis, which is the idea that the results observed are the product of chance. You will then need an alternative hypothesis, which is the idea that the results seen cannot be explained by chance alone. Finally, a test needs a significance level, which is the value the test statistic needs to take before it is decided that the null hypothesis cannot explain the difference. All statistical significance tests have these four aspects, and it is simply a matter of how these components are calculated that differentiate significance tests:
Some common statistical significance tests include the following:
To learn more about statistical significance, please refer to a statistics textbook, such as Statistics by David Freedman, Robert Pisani, and Roger Purves.
Data is a powerful method by which to understand the world. The ultimate goal for analytics is to turn data into information and knowledge. To accomplish this goal, statistics can be used to better understand data, especially descriptive statistics, and statistical significance testing.
One branch of descriptive statistics, univariate analysis, can be utilized to understand a single variable of data. Univariate analysis can be used to find the distribution of data by utilizing frequency distributions and quantiles. We can also find the central tendency of a variable by calculating the mean, median, and mode of data. It can also be used to find the dispersion of data using the range, standard deviation, and IQR. Univariate analysis can also be used to find outliers.
Bivariate analysis can also be used to understand the relationship between data. Using scatterplots, we can determine trends, changes in trends, periodic behavior, and anomalous points in regard to two variables. We can also use the Pearson correlation coefficient to measure the strength of a linear trend between the two variables. The Pearson correlation coefficient, however, is subject to scrutiny due to outliers or the number of data points used to calculate the coefficient. Additionally, just because two variables have a strong correlation coefficient does not mean that one variable causes the other variable.
Statistical significance testing can also provide important information about data. Statistical significance testing allows us to determine how likely certain outcomes are to occur by chance and can help us to understand whether the changes seen between groups are of consequence.
Now that we have the basic analytical tools necessary to understand data, we will now review SQL and how we can use it to manipulate a database in the next chapter.
Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.
If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.
Please Note: Packt eBooks are non-returnable and non-refundable.
Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:
If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:
Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.
You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.
Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.
When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.
For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.