Book Image

Python: End-to-end Data Analysis

By : Ivan Idris, Luiz Felipe Martins, Martin Czygan, Phuong Vo.T.H, Magnus Vilhelm Persson
Book Image

Python: End-to-end Data Analysis

By: Ivan Idris, Luiz Felipe Martins, Martin Czygan, Phuong Vo.T.H, Magnus Vilhelm Persson

Overview of this book

Data analysis is the process of applying logical and analytical reasoning to study each component of data present in the system. Python is a multi-domain, high-level, programming language that offers a range of tools and libraries suitable for all purposes, it has slowly evolved as one of the primary languages for data science. Have you ever imagined becoming an expert at effectively approaching data analysis problems, solving them, and extracting all of the available information from your data? If yes, look no further, this is the course you need! In this course, we will get you started with Python data analysis by introducing the basics of data analysis and supported Python libraries such as matplotlib, NumPy, and pandas. Create visualizations by choosing color maps, different shapes, sizes, and palettes then delve into statistical data analysis using distribution algorithms and correlations. You’ll then find your way around different data and numerical problems, get to grips with Spark and HDFS, and set up migration scripts for web mining. You’ll be able to quickly and accurately perform hands-on sorting, reduction, and subsequent analysis, and fully appreciate how data analysis methods can support business decision-making. Finally, you will delve into advanced techniques such as performing regression, quantifying cause and effect using Bayesian methods, and discovering how to use Python’s tools for supervised machine learning. The course provides you with highly practical content explaining data analysis with Python, from the following Packt books: 1. Getting Started with Python Data Analysis. 2. Python Data Analysis Cookbook. 3. Mastering Python Data Analysis. By the end of this course, you will have all the knowledge you need to analyze your data with varying complexity levels, and turn it into actionable insights.
Table of Contents (6 chapters)

Let's first get acquainted with two of Pandas' primary data structures: the Series and the DataFrame. They can handle the majority of use cases in finance, statistic, social science, and many areas of engineering.

A Series is a one-dimensional object similar to an array, list, or column in table. Each item in a Series is assigned to an entry in an index:

By default, if no index is passed, it will be created to have values ranging from 0 to N-1, where N is the length of the Series:

We can access the value of a Series by using the index:

This accessing method is similar to a Python dictionary. Therefore, Pandas also allows us to initialize a Series object directly from a Python dictionary:

Sometimes, we want to filter or rename the index of a Series created from a Python dictionary. At such times, we can pass the selected index list directly to the initial function, similarly to the process in the above example. Only elements that exist in the index list will be in the Series object. Conversely, indexes that are missing in the dictionary are initialized to default NaN values by Pandas:

The library also supports functions that detect missing data:

Similarly, we can also initialize a Series from a scalar value:

A Series object can be initialized with NumPy objects as well, such as ndarray. Moreover, Pandas can automatically align data indexed in different ways in arithmetic operations:

The DataFrame is a tabular data structure comprising a set of ordered columns and rows. It can be thought of as a group of Series objects that share an index (the column names). There are a number of ways to initialize a DataFrame object. Firstly, let's take a look at the common example of creating DataFrame from a dictionary of lists:

By default, the DataFrame constructor will order the column alphabetically. We can edit the default order by passing the column's attribute to the initializing function:

We can provide the index labels of a DataFrame similar to a Series:

We can construct a DataFrame out of nested lists as well:

Columns can be accessed by column name as a Series can, either by dictionary-like notation or as an attribute, if the column name is a syntactically valid attribute name:

To modify or append a new column to the created DataFrame, we specify the column name and the value we want to assign:

Using a couple of methods, rows can be retrieved by position or name:

A DataFrame object can also be created from different data structures such as a list of dictionaries, a dictionary of Series, or a record array. The method to initialize a DataFrame object is similar to the examples above.

Another common case is to provide a DataFrame with data from a location such as a text file. In this situation, we use the read_csv function that expects the column separator to be a comma, by default. However, we can change that by using the sep parameter:

While reading a data file, we sometimes want to skip a line or an invalid value. As for Pandas 0.16.2, read_csv supports over 50 parameters for controlling the loading process. Some common useful parameters are as follows:

Moreover, Pandas also has support for reading and writing a DataFrame directly from or to a database such as the read_frame or write_frame function within the Pandas module. We will come back to these methods later in this chapter.

Series

A

Series is a one-dimensional object similar to an array, list, or column in table. Each item in a Series is assigned to an entry in an index:

By default, if no index is passed, it will be created to have values ranging from 0 to N-1, where N is the length of the Series:

We can access the value of a Series by using the index:

This accessing method is similar to a Python dictionary. Therefore, Pandas also allows us to initialize a Series object directly from a Python dictionary:

Sometimes, we want to filter or rename the index of a Series created from a Python dictionary. At such times, we can pass the selected index list directly to the initial function, similarly to the process in the above example. Only elements that exist in the index list will be in the Series object. Conversely, indexes that are missing in the dictionary are initialized to default NaN values by Pandas:

The library also supports functions that detect missing data:

Similarly, we can also initialize a Series from a scalar value:

A Series object can be initialized with NumPy objects as well, such as ndarray. Moreover, Pandas can automatically align data indexed in different ways in arithmetic operations:

The DataFrame is a tabular data structure comprising a set of ordered columns and rows. It can be thought of as a group of Series objects that share an index (the column names). There are a number of ways to initialize a DataFrame object. Firstly, let's take a look at the common example of creating DataFrame from a dictionary of lists:

By default, the DataFrame constructor will order the column alphabetically. We can edit the default order by passing the column's attribute to the initializing function:

We can provide the index labels of a DataFrame similar to a Series:

We can construct a DataFrame out of nested lists as well:

Columns can be accessed by column name as a Series can, either by dictionary-like notation or as an attribute, if the column name is a syntactically valid attribute name:

To modify or append a new column to the created DataFrame, we specify the column name and the value we want to assign:

Using a couple of methods, rows can be retrieved by position or name:

A DataFrame object can also be created from different data structures such as a list of dictionaries, a dictionary of Series, or a record array. The method to initialize a DataFrame object is similar to the examples above.

Another common case is to provide a DataFrame with data from a location such as a text file. In this situation, we use the read_csv function that expects the column separator to be a comma, by default. However, we can change that by using the sep parameter:

While reading a data file, we sometimes want to skip a line or an invalid value. As for Pandas 0.16.2, read_csv supports over 50 parameters for controlling the loading process. Some common useful parameters are as follows:

Moreover, Pandas also has support for reading and writing a DataFrame directly from or to a database such as the read_frame or write_frame function within the Pandas module. We will come back to these methods later in this chapter.

The DataFrame

The

DataFrame is a tabular data structure comprising a set of ordered columns and rows. It can be thought of as a group of Series objects that share an index (the column names). There are a number of ways to initialize a DataFrame object. Firstly, let's take a look at the common example of creating DataFrame from a dictionary of lists:

By default, the DataFrame constructor will order the column alphabetically. We can edit the default order by passing the column's attribute to the initializing function:

We can provide the index labels of a DataFrame similar to a Series:

We can construct a DataFrame out of nested lists as well:

Columns can be accessed by column name as a Series can, either by dictionary-like notation or as an attribute, if the column name is a syntactically valid attribute name:

To modify or append a new column to the created DataFrame, we specify the column name and the value we want to assign:

Using a couple of methods, rows can be retrieved by position or name:

A DataFrame object can also be created from different data structures such as a list of dictionaries, a dictionary of Series, or a record array. The method to initialize a DataFrame object is similar to the examples above.

Another common case is to provide a DataFrame with data from a location such as a text file. In this situation, we use the read_csv function that expects the column separator to be a comma, by default. However, we can change that by using the sep parameter:

While reading a data file, we sometimes want to skip a line or an invalid value. As for Pandas 0.16.2, read_csv supports over 50 parameters for controlling the loading process. Some common useful parameters are as follows:

Moreover, Pandas also has support for reading and writing a DataFrame directly from or to a database such as the read_frame or write_frame function within the Pandas module. We will come back to these methods later in this chapter.

Pandas supports many essential functionalities that are useful to manipulate Pandas data structures. In this book, we will focus on the most important features regarding exploration and analysis.

The supported statistics method of a library is really important in data analysis. To get inside a big data object, we need to know some summarized information such as mean, sum, or quantile. Pandas supports a large number of methods to compute them. Let's consider a simple example of calculating the sum information of df5, which is a DataFrame object:

When we do not specify which axis we want to calculate sum information, by default, the function will calculate on index axis, which is axis 0:

We also have the skipna parameter that allows us to decide whether to exclude missing data or not. By default, it is set as true:

Another function that we want to consider is describe(). It is very convenient for us to summarize most of the statistical information of a data structure such as the Series and DataFrame, as well:

We can specify percentiles to include or exclude in the output by using the percentiles parameter; for example, consider the following:

Here, we have a summary table for common supported statistics functions in Pandas:

Function

Description

idxmin(axis), idxmax(axis)

This compute the index labels with the minimum or maximum corresponding values.

value_counts()

This compute the frequency of unique values.

count()

This return the number of non-null values in a data object.

mean(), median(), min(), max()

This return mean, median, minimum, and maximum values of an axis in a data object.

std(), var(), sem()

These return the standard deviation, variance, and standard error of mean.

abs()

This gets the absolute value of a data object.

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Reindexing and altering labels

Reindex

The supported statistics method of a library is really important in data analysis. To get inside a big data object, we need to know some summarized information such as mean, sum, or quantile. Pandas supports a large number of methods to compute them. Let's consider a simple example of calculating the sum information of df5, which is a DataFrame object:

When we do not specify which axis we want to calculate sum information, by default, the function will calculate on index axis, which is axis 0:

We also have the skipna parameter that allows us to decide whether to exclude missing data or not. By default, it is set as true:

Another function that we want to consider is describe(). It is very convenient for us to summarize most of the statistical information of a data structure such as the Series and DataFrame, as well:

We can specify percentiles to include or exclude in the output by using the percentiles parameter; for example, consider the following:

Here, we have a summary table for common supported statistics functions in Pandas:

Function

Description

idxmin(axis), idxmax(axis)

This compute the index labels with the minimum or maximum corresponding values.

value_counts()

This compute the frequency of unique values.

count()

This return the number of non-null values in a data object.

mean(), median(), min(), max()

This return mean, median, minimum, and maximum values of an axis in a data object.

std(), var(), sem()

These return the standard deviation, variance, and standard error of mean.

abs()

This gets the absolute value of a data object.

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Head and tail

In common

The supported statistics method of a library is really important in data analysis. To get inside a big data object, we need to know some summarized information such as mean, sum, or quantile. Pandas supports a large number of methods to compute them. Let's consider a simple example of calculating the sum information of df5, which is a DataFrame object:

When we do not specify which axis we want to calculate sum information, by default, the function will calculate on index axis, which is axis 0:

We also have the skipna parameter that allows us to decide whether to exclude missing data or not. By default, it is set as true:

Another function that we want to consider is describe(). It is very convenient for us to summarize most of the statistical information of a data structure such as the Series and DataFrame, as well:

We can specify percentiles to include or exclude in the output by using the percentiles parameter; for example, consider the following:

Here, we have a summary table for common supported statistics functions in Pandas:

Function

Description

idxmin(axis), idxmax(axis)

This compute the index labels with the minimum or maximum corresponding values.

value_counts()

This compute the frequency of unique values.

count()

This return the number of non-null values in a data object.

mean(), median(), min(), max()

This return mean, median, minimum, and maximum values of an axis in a data object.

std(), var(), sem()

These return the standard deviation, variance, and standard error of mean.

abs()

This gets the absolute value of a data object.

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Binary operations

Firstly, we

The supported statistics method of a library is really important in data analysis. To get inside a big data object, we need to know some summarized information such as mean, sum, or quantile. Pandas supports a large number of methods to compute them. Let's consider a simple example of calculating the sum information of df5, which is a DataFrame object:

When we do not specify which axis we want to calculate sum information, by default, the function will calculate on index axis, which is axis 0:

We also have the skipna parameter that allows us to decide whether to exclude missing data or not. By default, it is set as true:

Another function that we want to consider is describe(). It is very convenient for us to summarize most of the statistical information of a data structure such as the Series and DataFrame, as well:

We can specify percentiles to include or exclude in the output by using the percentiles parameter; for example, consider the following:

Here, we have a summary table for common supported statistics functions in Pandas:

Function

Description

idxmin(axis), idxmax(axis)

This compute the index labels with the minimum or maximum corresponding values.

value_counts()

This compute the frequency of unique values.

count()

This return the number of non-null values in a data object.

mean(), median(), min(), max()

This return mean, median, minimum, and maximum values of an axis in a data object.

std(), var(), sem()

These return the standard deviation, variance, and standard error of mean.

abs()

This gets the absolute value of a data object.

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Functional statistics

The

supported statistics method of a library is really important in data analysis. To get inside a big data object, we need to know some summarized information such as mean, sum, or quantile. Pandas supports a large number of methods to compute them. Let's consider a simple example of calculating the sum information of df5, which is a DataFrame object:

When we do not specify which axis we want to calculate sum information, by default, the function will calculate on index axis, which is axis 0:

We also have the skipna parameter that allows us to decide whether to exclude missing data or not. By default, it is set as true:

Another function that we want to consider is describe(). It is very convenient for us to summarize most of the statistical information of a data structure such as the Series and DataFrame, as well:

We can specify percentiles to include or exclude in the output by using the percentiles parameter; for example, consider the following:

Here, we have a summary table for common supported statistics functions in Pandas:

Function

Description

idxmin(axis), idxmax(axis)

This compute the index labels with the minimum or maximum corresponding values.

value_counts()

This compute the frequency of unique values.

count()

This return the number of non-null values in a data object.

mean(), median(), min(), max()

This return mean, median, minimum, and maximum values of an axis in a data object.

std(), var(), sem()

These return the standard deviation, variance, and standard error of mean.

abs()

This gets the absolute value of a data object.

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Function application

Pandas

There are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

Sorting

There

are two kinds of sorting method that we are interested in: sorting by row or column index and sorting by data value.

Firstly, we will consider methods for sorting by row and column index. In this case, we have the sort_index () function. We also have axis parameter to set whether the function should sort by row or column. The ascending option with the true or false value will allow us to sort data in ascending or descending order. The default setting for this option is true:

Series has a method order that sorts by value. For NaN values in the object, we can also have a special treatment via the na_position option:

Besides that, Series also has the sort() function that sorts data by value. However, the function will not return a copy of the sorted data:

If we want to apply sort function to a DataFrame object, we need to figure out which columns or rows will be sorted:

If we do not want to automatically save the sorting result to the current data object, we can change the setting of the inplace parameter to False.

In this section, we will focus on how to get, set, or slice subsets of Pandas data structure objects. As we learned in previous sections, Series or DataFrame objects have axis labeling information. This information can be used to identify items that we want to select or assign a new value to in the object:

If the data object is a DataFrame structure, we can also proceed in a similar way:

For label indexing on the rows of DataFrame, we use the ix function that enables us to select a set of rows and columns in the object. There are two parameters that we need to specify: the row and column labels that we want to get. By default, if we do not specify the selected column names, the function will return selected rows with all columns in the object:

Moreover, we have many ways to select and edit data contained in a Pandas object. We summarize these functions in the following table:

Method

Description

icol, irow

This selects a single row or column by integer location.

get_value, set_value

This selects or sets a single value of a data object by row or column label.

xs

This selects a single column or row as a Series by label.

Let's start with correlation and covariance computation between two data objects. Both the Series and DataFrame have a cov method. On a DataFrame object, this method will compute the covariance between the Series inside the object:

Usage of the correlation method is similar to the covariance method. It computes the correlation between Series inside a data object in case the data object is a DataFrame. However, we need to specify which method will be used to compute the correlations. The available methods are pearson, kendall, and spearman. By default, the function applies the spearman method:

We also have the corrwith function that supports calculating correlations between Series that have the same label contained in different DataFrame objects:

In this section, we will discuss missing, NaN, or null values, in Pandas data structures. It is a very common situation to arrive with missing data in an object. One such case that creates missing data is reindexing:

To manipulate missing values, we can use the isnull() or notnull() functions to detect the missing values in a Series object, as well as in a DataFrame object:

On a Series, we can drop all null data and index values by using the dropna function:

With a DataFrame object, it is a little bit more complex than with Series. We can tell which rows or columns we want to drop and also if all entries must be null or a single null value is enough. By default, the function will drop any row containing a missing value:

Another way to control missing values is to use the supported parameters of functions that we introduced in the previous section. They are also very useful to solve this problem. In our experience, we should assign a fixed value in missing cases when we create data objects. This will make our objects cleaner in later processing steps. For example, consider the following:

We can alse use the fillna function to fill a custom value in missing values:

In this section we will consider some advanced Pandas use cases.

Hierarchical indexing provides us with a way to work with higher dimensional data in a lower dimension by structuring the data object into multiple index levels on an axis:

In the preceding example, we have a Series object that has two index levels. The object can be rearranged into a DataFrame using the unstack function. In an inverse situation, the stack function can be used:

We can also create a DataFrame to have a hierarchical index in both axes:

The methods for getting or setting values or subsets of the data objects with multiple index levels are similar to those of the nonhierarchical case:

After grouping data into multiple index levels, we can also use most of the descriptive and statistics functions that have a level option, which can be used to specify the level we want to process:

The Panel is another data structure for three-dimensional data in Pandas. However, it is less frequently used than the Series or the DataFrame. You can think of a Panel as a table of DataFrame objects. We can create a Panel object from a 3D ndarray or a dictionary of DataFrame objects:

Each item in a Panel is a DataFrame. We can select an item, by item name:

Alternatively, if we want to select data via an axis or data position, we can use the ix method, like on Series or DataFrame:

Hierarchical indexing

Hierarchical indexing

provides us with a way to work with higher dimensional data in a lower dimension by structuring the data object into multiple index levels on an axis:

In the preceding example, we have a Series object that has two index levels. The object can be rearranged into a DataFrame using the unstack function. In an inverse situation, the stack function can be used:

We can also create a DataFrame to have a hierarchical index in both axes:

The methods for getting or setting values or subsets of the data objects with multiple index levels are similar to those of the nonhierarchical case:

After grouping data into multiple index levels, we can also use most of the descriptive and statistics functions that have a level option, which can be used to specify the level we want to process:

The Panel is another data structure for three-dimensional data in Pandas. However, it is less frequently used than the Series or the DataFrame. You can think of a Panel as a table of DataFrame objects. We can create a Panel object from a 3D ndarray or a dictionary of DataFrame objects:

Each item in a Panel is a DataFrame. We can select an item, by item name:

Alternatively, if we want to select data via an axis or data position, we can use the ix method, like on Series or DataFrame:

The Panel data

The Panel is

another data structure for three-dimensional data in Pandas. However, it is less frequently used than the Series or the DataFrame. You can think of a Panel as a table of DataFrame objects. We can create a Panel object from a 3D ndarray or a dictionary of DataFrame objects:

Each item in a Panel is a DataFrame. We can select an item, by item name:

Alternatively, if we want to select data via an axis or data position, we can use the ix method, like on Series or DataFrame:

We have finished covering the basics of the Pandas data analysis library. Whenever you learn about a library for data analysis, you need to consider the three parts that we explained in this chapter. Data structures: we have two common data object types in the Pandas library; Series and DataFrames. Method to access and manipulate data objects: Pandas supports many way to select, set or slice subsets of data object. However, the general mechanism is using index labels or the positions of items to identify values. Functions and utilities: They are the most important part of a powerful library. In this chapter, we covered all common supported functions of Pandas which allow us compute statistics on data easily. The library also has a lot of other useful functions and utilities that we could not explain in this chapter. We encourage you to start your own research, if you want to expand your experience with Pandas. It helps us to process large data in an optimized way. You will see more of Pandas in action later in this book.

Until now, we learned about two popular Python libraries: NumPy and Pandas. Pandas is built on NumPy, and as a result it allows for a bit more convenient interaction with data. However, in some situations, we can flexibly combine both of them to accomplish our goals.

Practice exercises

The link https://www.census.gov/2010census/csv/pop_change.csv contains an US census dataset. It has 23 columns and one row for each US state, as well as a few rows for macro regions such as North, South, and West.

  • Get this dataset into a Pandas DataFrame. Hint: just skip those rows that do not seem helpful, such as comments or description.
  • While the dataset contains change metrics for each decade, we are interested in the population change during the second half of the twentieth century, that is between, 1950 and 2000. Which region has seen the biggest and the smallest population growth in this time span? Also, which US state?

Advanced open-ended exercise:

  • Find more census data on the internet; not just on the US but on the world's countries. Try to find GDP data for the same time as well. Try to align this data to explore patterns. How are GDP and population growth related? Are there any special cases. such as countries with high GDP but low population growth or countries with the opposite history?