Pandas Guide
Pandas Guide
Pandas Guide
Table of contents i
1 Pandas Basic 2
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.2 DataFrame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Overview 6
2.1 Reading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Data operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.1 Row and column selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.2 Filter Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.3 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.4 Null values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.5 String operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.6 Count Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.7 Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Groupby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3.1 Groupby with column-names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3.2 Groupby with custom field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Unstack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5 Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.1 Merge with different files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.2 Merge table with itself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.6 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6.1 Creating index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6.2 Multiple index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6.3 Reset index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.7 Implement using Python-CSV library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.7.1 Read the file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.7.2 Display movies according to year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.7.3 operator.iemgetter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.7.4 Replace empty string with 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.7.5 collections.Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.7.6 collections.defaultdict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3 Numpy 27
3.1 Creating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2 Boolean indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.3 Reshaping arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.4 Concatenating the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
i
Table of contents
4 Data processing 31
4.1 Hierarchical indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.1 Creating multiple index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.2 Partial indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.1.3 Unstack the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.1.4 Column indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.1.5 Swap and sort level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.1.6 Summary statistics by level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.2 File operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2.1 Reading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2.2 Writing data to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.3.1 Many to one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.3.2 Inner and outer join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.3.3 Concatenating the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.4 Data transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4.1 Removing duplicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4.2 Replacing values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.5 Groupby and data aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.5.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.5.2 Iterating over group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.5.3 Data aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5 Time series 46
5.1 Dates and times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.1.1 Generate series of time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.1.2 Convert string to dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.1.3 Periods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.1.4 Time offsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.1.5 Index data with time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.2 Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.2.2 Resampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.2.3 Plotting the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.2.4 Moving windows functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
ii PythonDSP
Table of contents
Note:
• Created using Python-3.6.4 and Pandas-0.22.0
• CSV files can be downloaded from below link,
https://bitbucket.org/pythondsp/pandasguide/downloads/
Pandas Basic
1.1 Introduction
Data processing is important part of analyzing the data, because data is not always available in desired format.
Various processing are required before analyzing the data such as cleaning, restructuring or merging etc. Numpy,
Scipy, Cython and Panda are the tools available in python which can be used fast processing of the data. Further,
Pandas are built on the top of Numpy.
Pandas provides rich set of functions to process various types of data. Further, working with Panda is fast, easy
and more expressive than other tools. Pandas provides fast data processing as Numpy along with flexible data
manipulation techniques as spreadsheets and relational databases. Lastly, pandas integrates well with matplotlib
library, which makes it very handy tool for analyzing the data.
Note:
• In chapter 1, two important data structures i.e. Series and DataFrame are discussed.
• Chapter 2 shows the frequently used features of Pandas with example. And later chapters include various
other information about Pandas.
Pandas provides two very useful data structures to process the data i.e. Series and DataFrame, which are discussed
in this section.
1.2.1 Series
The Series is a one-dimensional array that can store various data types, including mix data types. The row labels
in a Series are called the index. Any list, tuple and dictionary can be converted in to Series using ‘series’ method
as shown below,
>>> type(s)
<class 'pandas.core.series.Series'>
2
Chapter 1. Pandas Basic
>>> type(ds)
<class 'pandas.core.series.Series'>
>>> print(ds)
date 2010-09-08
name IBM
price 10.2
shares 100
dtype: object
Note that in the tuple-conversion, the index are set to ‘0, 1, 2 and 3’. We can provide custom index names as
follows.
>>> print(f)
name FB
date 2001-08-02
shares 90
price 3.2
dtype: object
>>> f['shares']
90
>>> f[0]
'FB'
>>>
Elements of the Series can be accessed using index name e.g. f[‘shares’] or f[0] in below code. Further, specific
elements can be selected by providing the index in the list,
1.2.2 DataFrame
DataFrame is the widely used data structure of pandas. Note that, Series are used to work with one dimensional
array, whereas DataFrame can be used with two dimensional arrays. DataFrame has two different index i.e.
column-index and row-index.
The most common way to create a DataFrame is by using the dictionary of equal-length list as shown below.
Further, all the spreadsheets and text files are read as DataFrame, therefore it is very important data structure of
pandas.
>>> df = pd.DataFrame(data)
>>> type(df)
<class 'pandas.core.frame.DataFrame'>
>>> df
date name price shares
0 2001-12-01 AA 12.3 100
1 2012-02-10 IBM 10.3 30
2 2010-04-09 GOOG 32.2 90
Currently, the row index are set to 0, 1 and 2. These can be changed using ‘index’ attribute as below,
>>> df.index = ['one', 'two', 'three']
>>> df
date name price shares owner
one 2001-12-01 AA 12.3 100 Unknown
two 2012-02-10 IBM 10.3 30 Unknown
three 2010-04-09 GOOG 32.2 90 Unknown
Further, any column of the DataFrame can be set as index using ‘set_index()’ attribute, as shown below,
>>> df = df.set_index(['name'])
>>> df
date price shares owner
name
AA 2001-12-01 12.3 100 Unknown
IBM 2012-02-10 10.3 30 Unknown
GOOG 2010-04-09 32.2 90 Unknown
Data can be accessed in two ways i.e. using row and column index,
>>> # access data using column-index
>>> df['shares']
name
AA 100
IBM 30
GOOG 90
Name: shares, dtype: int64
4 PythonDSP
Chapter 1. Pandas Basic
Overview
In this chapter, various functionalities of pandas are shown with examples, which are explained in later chapters
as well.
In this section, two data files are used i.e. ‘titles.csv’ and ‘cast.csv’. The ‘titles.csv’ file contains the list
of movies with the releasing year; whereas ‘cast.csv’ file has five columns which store the title of movie,
releasing year, star-casts, type(actor/actress), characters and ratings for actors, as shown below,
6
Chapter 2. Overview
If we simply type the name of the DataFrame (i.e. cast in below code), then it will show the first thirty and last
twenty rows of the file along with complete list of columns. This can be limited using ‘set_options’ as below.
Further, at the end of the table total number of rows and columns will be displayed.
• len : ‘len’ commmand can be used to see the total number of rows in the file,
>>> len(titles)
50000
Note: head() and tail() commands can be used for remind ourselves about the header and contents of the file.
These two commands will show the first and last 5 lines respectively of the file. Further, we can change the total
number of lines to be displayed by these commands,
>>> titles.head(3)
title year
0 The Rising Son 1990
1 The Thousand Plane Raid 1969
2 Crucea de piatra 1993
In this section, various useful data operations for DataFrame are shown.
Any row or column of the DataFrame can be selected by passing the name of the column or rows. After selecting
one from DataFrame, it becomes one-dimensional therefore it is considered as Series.
• ix : use ‘ix’ command to select a row from the DataFrame.
>>> t = titles['title']
>>> type(t)
<class 'pandas.core.series.Series'>
>>> t.head()
0 The Rising Son
1 The Thousand Plane Raid
2 Crucea de piatra
(continues on next page)
>>> titles.ix[0]
title The Rising Son
year 1990
Name: 0, dtype: object
>>>
Data can be filtered by providing some boolean expression in DataFrame. For example, in below code, movies
which released after 1985 are filtered out from the DataFrame ‘titles’ and stored in a new DataFrame i.e. after85.
Note: When we pass the boolean results to DataFrame, then panda will show all the results which corresponds
to True (rather than displaying True and False), as shown in above code. Further, ‘& (and)’ and ‘| (or)’ can be
used for joining two conditions as shown below,**
In below code all the movies in decade 1990 (i.e. 1900-1999) are selected. Also ‘t = titles’ is used for simplicity
purpose only.
2.2.3 Sorting
8 PythonDSP
Chapter 2. Overview
Note that in above filtering operation, the data is sorted by index i.e. by default ‘sort_index’ operation is used as
shown below,
To sort the data by values, the ‘sort_value’ option can be used. In below code, data is sorted by year now,
Note that, various columns may contains no values, which are usually filled as NaN. For example, rows 3-4 of casts
are NaN as shown below,
>>> casts.ix[3:4]
title year name type character n
3 Secret in Their Eyes 2015 $hutter actor 2002 Dodger Fan NaN
4 Steve Jobs 2015 $hutter actor 1988 Opera House Patron NaN
These null values can be easily selected, unselected or contents can be replaced by any other values e.g. empty
strings or 0 etc. Various examples of null values are shown in this section.
• ‘isnull’ command returns the true value if any row of has null values. Since the rows 3-4 has NaN value,
therefore, these are displayed as True.
>>> c = casts
>>> c['n'].isnull().head()
0 False
1 False
2 False
3 True
4 True
Name: n, dtype: bool
>>> c['n'].notnull().head()
0 True
1 True
2 True
3 False
4 False
Name: n, dtype: bool
• To display the rows with null values, the condition must be passed in the DataFrame,
>>> c[c['n'].isnull()].head(3)
title year name type character n
3 Secret in Their Eyes 2015 $hutter actor 2002 Dodger Fan NaN
4 Steve Jobs 2015 $hutter actor 1988 Opera House Patron NaN
5 Straight Outta Compton 2015 $hutter actor Club Patron NaN
>>>
• NaN values can be fill by using fillna, ffill(forward fill), and bfill(backward fill) etc. In below code,
‘NaN’ values are replace by NA. Further, example of ffill and bfill are shown in later part of the tutorial,
Various string operations can be performed using ‘.str.’ option. Let’s search for the movie “Maa” first,
>>> t = titles
>>> t[t['title'] == 'Maa']
title year
38880 Maa 1968
>>>
There is only one movie in the list. Now, we want to search all the movies which starts with ‘Maa’. The ‘.str.’
option is required for such queries as shown below,
Total number of occurrences can be counted using ‘value_counts()’ option. In following code, total number of
movies are displayed base on years.
>>> t['year'].value_counts().head()
2016 2363
2017 2138
2015 1849
2014 1701
2013 1609
Name: year, dtype: int64
10 PythonDSP
Chapter 2. Overview
2.2.7 Plots
Pandas supports the matplotlib library and can be used to plot the data as well. In previous section, the total
numbers of movies/year were filtered out from the DataFrame. In the below code, those values are saved in new
DataFrame and then plotted using panda,
Following plot will be generated from above code, which does not provide any useful information.
It’s better to sort the years (i.e. index) first and then plot the data as below. Here, the plot shows that number
of movies are increasing every year.
>>> p.sort_index().plot()
<matplotlib.axes._subplots.AxesSubplot object at 0xa9cd134c>
>>> plt.show()
Now, the graph provide some useful information i.e. number of movies are increasing each year.
2.3 Groupby
Data can be grouped by columns-headers. Further, custom formats can be defined to group the various elements
of the DataFrame.
In Section Count Values, the value of movies/year were counted using ‘count_values()’ method. Same can be
achieve by ‘groupby’ method as well. The ‘groupby’ command return an object, and we need to an additional
functionality to it to get some results. For example, in below code, data is grouped by ‘year’ and then size()
command is used. The size() option counts the total number for rows for each year; therefore the result of below
code is same as ‘count_values()’ command.
>>> cg = c.groupby(['year']).size()
>>> cg.plot()
<matplotlib.axes._subplots.AxesSubplot object at 0xa9f14b4c>
>>> plt.show()
>>>
12 PythonDSP
Chapter 2. Overview
• Further, groupby option can take multiple parameters for grouping. For example, we want to group the
movies of the actor ‘Aaron Abrams’ based on year,
>>> c = casts
>>> cf = c[c['name'] == 'Aaron Abrams']
>>> cf.groupby(['year']).size().head()
year
2003 2
2004 2
2005 2
2006 1
2007 2
dtype: int64
>>>
Above list shows that year-2003 is found in two rows with name-entry as ‘Aaron Abrams’. In the other word, he
did 2 movies in 2003.
• Next, we want to see the list of movies as well, then we can pass two parameters in the list as shown below,
In above code, the groupby operation is performed on the ‘year’ first and then on ‘title’. In the other word, first
all the movies are grouped by year. After that, the result of this groupby is again grouped based on titles. Note
that, first group command arranged the year in order i.e. 2003, 2004 and 2005 etc.; then next group command
arranged the title in alphabetical order.
• Next, we want to do grouping based on maximum ratings in a year; i.e. we want to group the items by year
and see the maximum rating in those years,
>>> c.groupby(['year']).n.max().head()
year
1912 6.0
1913 14.0
1914 39.0
1915 14.0
1916 35.0
Name: n, dtype: float64
Above results show that the maximum rating in year 1912 is 6 for Aaron Abrams.
• Similarly, we can check for the minimum rating,
>>> c.groupby(['year']).n.min().head()
year
1912 6.0
1913 1.0
1914 1.0
1915 1.0
1916 1.0
Name: n, dtype: float64
>>> c.groupby(['year']).n.mean().head()
year
1912 6.000000
1913 4.142857
1914 7.085106
1915 4.236111
1916 5.037736
Name: n, dtype: float64
Suppose we want to group the data based on decades, then we need to create a custom groupby field,
2.4 Unstack
Before understanding the unstack, let’s consider one case from cast.csv file. In following code, the data is grouped
by decade and type i.e. actor and actress.
14 PythonDSP
Chapter 2. Overview
>>> c = casts
>>> c.groupby( [c['year']//10*10, 'type'] ).size().head(8)
year type
1910 actor 384
actress 285
1920 actor 710
actress 411
1930 actor 2628
actress 820
1940 actor 3014
actress 983
dtype: int64
>>>
Now we want to compare and plot the total number of actors and actresses in each decade. One solution to
this problem is to grab even and odd rows separately and plot the data, which is quite complicated operation if
types has more varieties e.g. new-actor, new-actress and teen-actors etc. A simple solution to such problem is the
‘unstack’, which allows to create a new DataFrame based on the grouped Dataframe, as shown below.
• Since we want a plot based on actors and actress, therefore first we need to group the data based on ‘type’
as below,
>>> c = casts
>>> c_decade = c.groupby( ['type', c['year']//10*10] ).size()
>>> c_decade
type year
actor 1910 384
1920 710
1930 2628
[...]
actress 1910 285
1920 411
1930 820
[...]
dtype: int64
>>>
• Now we can create a new DataFrame using ‘unstack’ command. The ‘unstack’ command creates a new
DataFrame based on index,
>>> c_decade.unstack()
year 1910 1920 1930 1940 1950 1960 1970 1980 1990 [...]
type
actor 384 710 2628 3014 2877 2775 3044 3565 5108 [...]
actress 285 411 820 983 1015 968 1299 1989 2544 [...]
>>> c_decade.unstack().plot()
<matplotlib.axes._subplots.AxesSubplot object at 0xb1cec56c>
>>> plt.show()
>>> c_decade.unstack().plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot object at 0xa8bf778c>
>>> plt.show()
Below figure will be generated from above command. Note that in the plot, actor and actress are plot separately
in the groups.
• To plot the data side by side, use unstack(0) option as shown below (by default unstack(-1) is used),
>>> c_decade.unstack(0)
type actor actress
year
1910 384 285
1920 710 411
1930 2628 820
1940 3014 983
1950 2877 1015
1960 2775 968
1970 3044 1299
1980 3565 1989
1990 5108 2544
2000 10368 5831
2010 15523 8853
2020 4 3
>>> c_decade.unstack(0).plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot object at 0xb1d218cc>
>>> plt.show()
16 PythonDSP
Chapter 2. Overview
2.5 Merge
Usually, different data of same project are available in various files. To get the useful information from these files,
we need to combine these files. Also, we need to merge to different data in the same file to get some specific
information. In this section, we will understand these two merges i.e. merge with different file and merge with
same file.
In this section, we will merge the data of two table i.e. ‘release_dates.csv’ and ‘cast.csv’. The ‘release_dates.csv’
file contains the release date of movies in different countries.
• First, load the ‘release_dates.csv’ file, which contains the release dates of some of the movies, listed in
‘cast.csv’. Following are the content of ‘release_dates.csv’ file,
>>> release = pd.read_csv('release_dates.csv', index_col=None)
>>> release.head()
title year country date
0 #73, Shaanthi Nivaasa 2007 India 2007-06-15
1 #Beings 2015 Romania 2015-01-29
2 #Declimax 2018 Netherlands 2018-01-21
3 #Ewankosau saranghaeyo 2015 Philippines 2015-01-21
4 #Horror 2015 USA 2015-11-20
>>> casts.head()
title year name type character n
0 Closet Monster 2015 Buffy #1 actor Buffy 4 31.0
1 Suuri illusioni 1985 Homo $ actor Guests 22.0
2 Battle of the Sexes 2017 $hutter actor Bobby Riggs Fan 10.0
3 Secret in Their Eyes 2015 $hutter actor 2002 Dodger Fan NaN
4 Steve Jobs 2015 $hutter actor 1988 Opera House Patron NaN
• Let’s we want to see the release date of the movie ‘Amelia’. For this first, filter out the Amelia from the
DataFrame ‘cast’ as below. There are only two entries for the movie Amelia.
• Next, we will see the entries of movie ‘Amelia’ in release dates as below. In the below result, we can see that
there are two different release years for the movie i.e. 1966 and 2009.
• Since there is not entry for Amelia-1966 in casts DataFrame, therefore merge command will not merge the
Amelia-1966 release dates. In following results, we can see that only Amelia 2009 release dates are merges
with casts DataFrame.
>>> c_amelia.merge(release).head()
title year name type character n country date
0 Amelia 2009 Aaron Abrams actor Slim Gordon 8.0 Canada 2009-10-23
1 Amelia 2009 Aaron Abrams actor Slim Gordon 8.0 USA 2009-10-23
2 Amelia 2009 Aaron Abrams actor Slim Gordon 8.0 Australia 2009-11-12
3 Amelia 2009 Aaron Abrams actor Slim Gordon 8.0 Singapore 2009-11-12
4 Amelia 2009 Aaron Abrams actor Slim Gordon 8.0 Ireland 2009-11-13
Suppose, we want see the list of co-actors in the movies. For this, we need to merge the table with itself based on
the title and year, as shown below. In the below code, co-star for actor ‘Aaron Abrams’ are displayed,
• First, filter out the results for ‘Aaron Abrams’,
• Next, to find the co-stars, merge the DataFrame with itself based on ‘title’ and ‘year’ i.e. for being a co-star,
the name of the movie and the year must be same,
• Note that ‘casts’ is used inside the bracket instead of c.
The problem with above joining is that it displays the ‘Aaron Abrams’ as his co-actor as well (see first row). This
problem can be avoided as below,
18 PythonDSP
Chapter 2. Overview
2.6 Index
In the previous section, we saw some uses of index for sorting and plotting the data. In this section, index are
discussed in detail.
Index is very important tool in pandas. It is used to organize the data and to provide us fast access to data. In
this section, time for data-access are compared for the data with and without indexing. For this section, Jupyter
notebook is used as ‘%%timeit’ is very easy to use in it to compare the time required for various access-operations.
import pandas as pd
cast = pd.read_csv('cast.csv', index_col=None)
cast.head()
%%time
‘%%timeit’ can be used for more precise results as it run the shell various times and display the average time; but
it will not show the output of the shell,
%%timeit
‘set_index’ can be used to create an index for the data. Note that, in below code, ‘title’ is set at index, therefore
index-numbers are replaced by ‘title’ (see the first column).
c = cast.set_index(['title'])
c.head(4)
To use the above indexing, ‘.loc’ should be used for fast operations,
%%time
%%timeit
** We can see that, there is performance improvement (i.e. 11ms to 6ms) using indexing, because speed will
increase further if the index are in sorted order. **
Next, we will sort the index and perform the filter operation,
cs = cast.set_index(['title']).sort_index()
cs.tail(4)
%%time
Now, filtering is completing in around ‘0.5 ms’ (rather than 4 ms), as shown by below results,
%%timeit
>>> cm.loc['Macbeth']
year name type character
n
4.0 1916 Spottiswoode Aitken actor Duncan
6.0 1916 Mary Alden actress Lady Macduff
18.0 1948 William Alland actor Second Murderer
21.0 1997 Stevie Allen actor Murderer
NaN 2015 Darren Adamson actor Soldier
NaN 1948 Robert Alan actor Third Murderer
NaN 2016 John Albasiny actor Doctor
NaN 2014 Moyo Akand? actress Witch
In above result, ‘title’ is removed from the index list, which represents that there is one more level of index, which
can be used for filtering. Lets filter the data again with second index as well,
If there is only one match data, then Series will return (instead of DataFrame),
20 PythonDSP
Chapter 2. Overview
year 1916
name Spottiswoode Aitken
type actor
character Duncan
Name: 4.0, dtype: object
Index can be reset using ‘reset_index’ command. Let’s look at the ‘cm’ DataFrame again.
cm.head(2)
In ‘cm’ DataFrame, there are two index; and one of these i.e. n is removed using ‘reset_index’ command.
Note that, all the above logic can be implemented using python-csv library as well. In this section, some of the
logics of above sections are re-implemented using python-csv library. By looking at following examples, we can
see that how easy is it to work with pandas as compare to python-csv library. However, we have more fun with
python built-in libraries,
import csv
titles = list(csv.DictReader(open('titles.csv')))
titles[0:5] # display first 5 rows
for k, v in titles[0].items():
print(k, ':', v)
2.7.3 operator.iemgetter
casts = list(csv.DictReader(open('cast.csv')))
casts[3:5]
22 PythonDSP
Chapter 2. Overview
2.7.5 collections.Counter
2.7.6 collections.defaultdict
d = defaultdict(list)
for row in titles:
d[row['year']].append(row['title'])
xx=[]
yy=[]
for k, v in d.items():
xx.append(k)# = k
yy.append(len(v))# = len(v)
plt.plot(sorted(xx), yy)
plt.show()
24 PythonDSP
Chapter 2. Overview
dcf
defaultdict(<class 'list'>, {
'2017': ['#FromJennifer', 'The Go-Getters'],
'2011': ['388 Arletta Avenue', 'Jesus Henry Christ', 'Jesus Henry Christ', 'Take This Waltz', 'The␣
˓→Chicago 8'], '2009': ['Amelia', 'At Home by Myself... with You'],
(continues on next page)
26 PythonDSP
Chapter 3
Numpy
Numerical Python (Numpy) is used for performing various numerical computation in python. Calculations using
Numpy arrays are faster than the normal python array. Further, pandas are build over numpy array, therefore
better understanding of python can help us to use pandas more effectively.
Defining multidimensional arrays are very easy in numpy as shown in below examples,
27
3.2. Boolean indexing
>>> # add 2 to e
>>> e2 = e + 2
>>> e2
array([[ 3., 2., 2.],
[ 2., 3., 2.],
[ 2., 2., 3.]])
Boolean indexing is very important feature of numpy, which is frequently used in pandas,
28 PythonDSP
Chapter 3. Numpy
30 PythonDSP
Chapter 4
Data processing
Most of programming work in data analysis and modeling is spent on data preparation e.g. loading, cleaning and
rearranging the data etc. Pandas along with python libraries gives us provide us a high performance, flexible and
high level environment for processing the data.
In chapter 1, we saw basics of pandas; then various examples are shown in chapter 2 for better understanding of
pandas; whereas chapter 3 presented some basics of numpy. In this chapter, we will see some more functionality
of pandas to process the data effectively.
Hierarchical indexing is an important feature of pandas that enable us to have multiple index levels. We already
see an example of it in Section Multiple index . In this section, we will learn more about indexing and access to
data with these indexing.
• There are two level of index here i.e. (a, b) and (obj1, . . . , obj4). The index can be seen using ‘index’
command as shown below,
>>> data.index
MultiIndex(levels=[['a', 'b'], ['obj1', 'obj2', 'obj3', 'obj4']],
labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 2, 3, 0, 1, 2, 3]])
31
4.1. Hierarchical indexing
>>> data['b']
obj1 15
obj2 25
obj3 35
obj4 25
dtype: int64
• Further, the data can be extracted based on inner level i.e. ‘obj’. Below result shows the two available values
for ‘obj2’ in the Series.
We saw the use of unstack operation in the Section Unstack . Unstack changes the row header to
column header. Since the row index is changed to column index, therefore the Series will become the
DataFrame in this case. Following are the some more example of unstacking the data,
• ‘stack()’ operation converts the column index to row index again. In above code, DataFrame ‘d’ has ‘obj’ as
column index, this can be converted into row index using ‘stack’ operation,
>>> d.stack()
a obj1 10
obj2 20
obj3 30
obj4 40
b obj1 15
(continues on next page)
32 PythonDSP
Chapter 4. Data processing
Remember that, the column indexing is possible for DataFrame only (not for Series), because column-indexing
require two dimensional data. Let’s create a new DataFrame as below for understanding the columns with multiple
index,
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(12).reshape(4, 3),
... index = [['a', 'a', 'b', 'b'], ['one', 'two', 'three', 'four']],
... columns = [['num1', 'num2', 'num3'], ['red', 'green', 'red']]
... )
>>>
>>> df
num1 num2 num3
red green red
a one 0 1 2
two 3 4 5
b three 6 7 8
four 9 10 11
>>>
• Note that, in previous section, we used the numbers for stack and unstack operation e.g. unstack(0) etc. We
can give name to index as well as below,
>>> df.index.names=['key1', 'key2']
>>> df.columns.names=['n', 'color']
>>> df
n num1 num2 num3
color red green red
key1 key2
a one 0 1 2
two 3 4 5
b three 6 7 8
four 9 10 11
• Now, we can perform the partial indexing operations. In following code, various ways to access the data in
a DataFrame are shown,
>>> # accessing the column for num1
>>> df['num1'] # df.ix[:, 'num1']
color red
key1 key2
a one 0
two 3
(continues on next page)
We can swap the index level using ‘swaplevel’ command, which takes two level-numbers as input,
Levels can be sorted using ‘sort_index’ command. In below code, data is sorted by ‘key2’ names i.e. key2 is
arranged alphabatically,
>>> df.sort_index(level='key2')
n num1 num2 num3
color red green red
key1 key2
b four 9 10 11
a one 0 1 2
b three 6 7 8
a two 3 4 5
>>>
We saw the example of groupby command in Section Groupby. Pandas provides some easier ways to perform those
operations using ‘level’ shown below,
34 PythonDSP
Chapter 4. Data processing
In this section, various methods for reading and writing the files are discussed.
Pandas supports various types of file format e.g. csv, text, excel and different database etc. Files are often stored
in different formats as well e.g. files may or may not contain header, footer and comments etc.; therefore we need
to process the content of file. Pandas provides various features which can process some of the common processing
while reading the file. Some of these processing are shown in this section.
• Files can be read using ‘read_csv’, ‘read_table’ or ‘DataFrame.from_csv’ options, as shown below. Note
that, the output of all these methods are same, but we need to provide different parameters to read the file
correctly.
Following are the contents of ‘ex1.csv’ file,
$ cat ex1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
Below are the outputs of different file reading methods. ‘read_csv’ is general purpose method for reading the files,
hence this method is used for rest of the tutorial,
>>> # DataFrame.from_csv
>>> df = pd.DataFrame.from_csv('ex1.csv', index_col=None)
>>> df
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
>>> # read_csv
>>> df = pd.read_csv('ex1.csv')
>>> df
a b c d message
0 1 2 3 4 hello
1 5 6 7 8 world
2 9 10 11 12 foo
>>> # read_table
(continues on next page)
• Note that, in above outputs, the headers are added from the file; but not all the files contain header. In this
case, we need to explicitly define the header as below,
Following are the contents of ‘ex2.csv’ file,
$ cat ex2.csv
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,food
Since header is not present in above file, therefore we need to provide the “header” argument explicitly.
$ cat csv_mindex.csv
key1,key2,value1,value2
one,a,1,2
one,b,3,4
one,c,5,6
one,d,7,8
two,a,9,10
two,b,11,12
two,c,13,14
two,d,15,16
36 PythonDSP
Chapter 4. Data processing
• Some files may contain additional information or comments, therefore we need to remove these information
for processing the data. This can be done by using ‘skiprows’ command,
Following are the content of ‘ex4.csv’ file,
$ cat ex4.csv
# hey!
a,b,c,d,message
# just wanted to make things more difficult for you
# who reads CSV files with computers, anyway?
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foodh
In above results, lines 0, 2 and 3 contains some comments. These can be removed as follows,
The ‘to_csv’ command is used to save the file. In following code, previous data ‘d’ is saved in two files i.e.
d_out.csv and d_out2.csv with and without index respectively,
>>> d.to_csv('d_out.csv')
$ cat d_out.csv
,a,b,c,d,message
0,1,2,3,4,hello
1,5,6,7,8,world
2,9,10,11,12,foo
$ cat d_out2.csv
0,1,2,3,4,hello
1,5,6,7,8,world
2,9,10,11,12,foo
4.3 Merge
Merge or joins operations combine the data sets by liking rows using one or more keys. The ‘merge’ function is
the main entry point for using these algorithms on the data. Let’s understand this by following examples,
>>> df1 = pd.DataFrame({ 'key' : ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
... 'data1' : range(7)})
>>> df1
data1 key
0 0 b
1 1 b
2 2 a
3 3 c
4 4 a
5 5 a
6 6 b
• ‘Many to one’ merge joins the Cartesian product of the rows, e.g. df1 and df2 has total 3 and 2 rows of ‘b’
respectively, therefore join will result in total 6 rows. Further, it is better to define ‘on’ keyword while using
the joins, as it makes code more readable,
• In previous case, both the DataFrame have the same header ‘key’. In the following example data are joined
based on different keys using ‘left_on’ and ‘right_on’ keywords,
>>> # data is same as previous, only 'key' is replaces with 'key1' and 'key2'
>>> df1 = pd.DataFrame({ 'key1' : ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
... 'data1' : range(7)})
>>> df2 = pd.DataFrame({ 'key2' : ['a', 'b', 'd', 'b'],
... 'data1' : range(4)})
38 PythonDSP
Chapter 4. Data processing
In previous example, we can see that uncommon entries in DataFrame ‘df1’ and ‘df2’ are missing from the merge
e.g. ‘d’ is not in the merged data. This is an example of ‘inner join’ where only common keys are merged together.
By default, pandas perform the inner join. To perform outer join, we need to use ‘how’ keyword which can have 3
different values i.e. ‘left’, ‘right’ and ‘outer’. ‘left’ option takes the left DataFrame and merge all it’s entries with
other DataFrame. Similarly, ‘right’ option merge the entries of the right DataFrame with left DataFrame. Lastly,
the ‘outer’ option merge all the entries from both the DataFrame, as shown below. Note that, the missing entries
after joining the table are represented as ‘NaN’.
>>> # left join
>>> pd.merge(df1, df2, left_on='key1', right_on='key2', how="left")
data1_x key1 data1_y key2
0 0 b 1.0 b
1 0 b 3.0 b
2 1 b 1.0 b
3 1 b 3.0 b
4 2 a 0.0 a
5 3 c NaN NaN
6 4 a 0.0 a
7 5 a 0.0 a
8 6 b 1.0 b
9 6 b 3.0 b
We saw concatenation of data in Numpy. Pandas concatenation is more generalized than Numpy. It allows
concatenation based on union or intersection of data along with labeling to visualize the grouping as shown in this
section,
>>> s1
a 0
b 1
dtype: int64
>>> s2
c 2
d 1
e 3
dtype: int64
>>> s3
a 4
e 7
dtype: int64
• In above results , it is difficult to identify the different pieces of concatenate operation. We can provide ‘keys’
to make the operation identifiable,
40 PythonDSP
Chapter 4. Data processing
Note: Above concatenate operation are the union of two data set i.e. it is outer join. We can use “join=’inner’ ”
for intersection of data.
• Concatenating the DataFrame is same as above. Following is the example of the concatenation of DataFrame.
Note that ‘df1’ and ‘df2’ are defined at the beginning of this section.
• We can pass the DataFrame as dictionary as well for the concatenation operation. In this case, the keys of
the dictionary will be used as ‘keys’ for the operation,
In previous section, we saw various operations to join the various data. Next, important step is the data trans-
formation i.e. cleaning and filtering the data e.g. removing the duplicate entries and replacing the NaN values
etc.
• Removing duplicate entries are quite easy with ‘drop_duplicates’ command. Also, ‘duplicate()’ command
can be used to check the duplicate entries as shown below,
• Currently, last entry is removed by drop_duplicates commnad. If we want to keep the last entry, then ‘keep’
keyword can be used,
>>> df.drop_duplicates(keep="last")
k1 k2
1 one 1
2 one 2
4 two 3
6 two 4
>>>
• We can drop all the duplicate values from based on the specific columns as well,
42 PythonDSP
Chapter 4. Data processing
4.5.1 Basics
We saw various groupby operation in Section Groupby. Here, some more features of gropby operations are discussed.
Let’s create a DataFrame first,
• Now, create a group based on ‘k1’ and find the mean value as below. In the following code, rows (0, 1, 4)
and (2, 3) are grouped together. Therefore mean values are 3 and 2.5.
• The groupby operation supports iteration which generates the tuple with two values i.e. group-name and
data.
• If groupby operation is performed based on multiple keys, then it will generate a tuple for keys as well,
44 PythonDSP
Chapter 4. Data processing
>>> gp1.max()
k1
a 4
b 3
Name: data1, dtype: int64
>>> gp2.min()
k1 k2
a one 2
two 3
b one 3
two 2
Name: data1, dtype: int64
Time series
A series of time can be generated using ‘date_range’ command. In below code, ‘periods’ is the total number of
samples; whereas freq = ‘M’ represents that series must be generated based on ‘Month’.
• By default, pandas consider ‘M’ as end of the month. Use ‘MS’ for start of the month. Similarly, other
options are also available for day (‘D’), business days (‘B’) and hours (‘H’) etc.
• Similarly, we can generate the time series using ‘start’ and ‘end’ parameters as below,
>>> rng = pd.date_range(start = '2015 Jul 2 10:15', end = '2015 July 12', freq = '12H')
>>> rng
DatetimeIndex(['2015-07-02 10:15:00', '2015-07-02 22:15:00',
'2015-07-03 10:15:00', '2015-07-03 22:15:00',
'2015-07-04 10:15:00', '2015-07-04 22:15:00',
'2015-07-05 10:15:00', '2015-07-05 22:15:00',
'2015-07-06 10:15:00', '2015-07-06 22:15:00',
'2015-07-07 10:15:00', '2015-07-07 22:15:00',
'2015-07-08 10:15:00', '2015-07-08 22:15:00',
'2015-07-09 10:15:00', '2015-07-09 22:15:00',
'2015-07-10 10:15:00', '2015-07-10 22:15:00',
(continues on next page)
46
Chapter 5. Time series
>>> rng = pd.date_range(start = '2015 Jul 2 10:15', end = '2015 July 12', freq = '12H', tz=
˓→'Asia/Kolkata')
>>> rng
DatetimeIndex(['2015-07-02 10:15:00+05:30', '2015-07-02 22:15:00+05:30',
'2015-07-03 10:15:00+05:30', '2015-07-03 22:15:00+05:30',
'2015-07-04 10:15:00+05:30', '2015-07-04 22:15:00+05:30',
'2015-07-05 10:15:00+05:30', '2015-07-05 22:15:00+05:30',
'2015-07-06 10:15:00+05:30', '2015-07-06 22:15:00+05:30',
'2015-07-07 10:15:00+05:30', '2015-07-07 22:15:00+05:30',
'2015-07-08 10:15:00+05:30', '2015-07-08 22:15:00+05:30',
'2015-07-09 10:15:00+05:30', '2015-07-09 22:15:00+05:30',
'2015-07-10 10:15:00+05:30', '2015-07-10 22:15:00+05:30',
'2015-07-11 10:15:00+05:30', '2015-07-11 22:15:00+05:30'],
dtype='datetime64[ns, Asia/Kolkata]', freq='12H')
>>>
• Further, we can change the time zone of the data for various comparison,
>>> type(rng[0])
<class 'pandas.tslib.Timestamp'>
>>>
Dates in string formats can be converted into time stamp using ‘to_datetime’ option as below,
5.1.3 Periods
Periods represents the time span e.g. days, years, quarter or month etc. Period class in pandas allows us to convert
the frequency easily.
In following code, period is generated using ‘Period’ command with frequency ‘M’. Note that, when we use ‘asfreq’
operation with ‘start’ operation the date is ‘01’ where as it is ‘31’ with ‘end’ option.
We can perform various arithmetic operation on periods. All the operations will be performed based on ‘freq’,
48 PythonDSP
Chapter 5. Time series
Conversion of string-dates to period is the two step process, i.e. first we need to convert the string to date format
and then convert the dates in periods as shown below,
>>> prd
PeriodIndex(['2013-02', '2012-02', '2013-02'], dtype='int64', freq='M')
>>> prd.to_timestamp()
DatetimeIndex(['2013-02-01', '2012-02-01', '2013-02-01'], dtype='datetime64[ns]', freq=None)
>>> prd.to_timestamp(how='end')
DatetimeIndex(['2013-02-28', '2012-02-29', '2013-02-28'], dtype='datetime64[ns]', freq=None)
>>>
Time offset can be defined as follows. Further we can perform various operations on time as as well e.g. adding
and subtracting etc.
In this section, time is used as index for Series and DataFrame; and then various operations are performed on
these data structures.
• First, create a time series using ‘date_range’ option as below.
• Next, make another temperature series ‘stemp’ and create a DataFrame using ‘stemp’ and ‘atemp’ as below,
50 PythonDSP
Chapter 5. Time series
• We can add one more column to DataFrame ‘temp’ which shows the temperature differences between these
two cities,
5.2 Application
In previous section, we saw some basics of time series. In this section, we will learn some usage of time series with
an example,
5.2.1 Basics
• If we check the format of ‘date’ column, we will find that it is string (not the date),
>>> d = df.date[0]
>>> d
'1990-02-01 00:00:00'
>>> type(d)
<class 'str'>
>>>
>>> df.head()
date AA GE IBM MSFT
0 1990-02-01 4.98 2.87 16.79 0.51
1 1990-02-02 5.04 2.87 16.89 0.51
2 1990-02-05 5.07 2.87 17.32 0.51
3 1990-02-06 5.01 2.88 17.56 0.51
4 1990-02-07 5.04 2.91 17.93 0.51
52 PythonDSP
Chapter 5. Time series
• Before going further, let’s check the name of the index as it will be used at various places along with plotting
the data, where index will be used automatically for plots. Note that, data is used as columns as well
as index by using ‘drop’ keyword.
>>> # check the name of the index
>>> df.index.name
'date'
>>>
• Data can be accessed by providing the date in any valid format, as shown below,
>>> # all four commands have same results
>>> # stocks.ix['1990, 02, 01']
>>> # stocks.ix['1990-02-01']
>>> # stocks.ix['1990/02/01']
>>> stocks.ix['1990-Feb-01']
date 1990-02-01 00:00:00
AA 4.98
GE 2.87
IBM 16.79
MSFT 0.51
Name: 1990-02-01 00:00:00, dtype: object
>>>
• We can display the results in between some range with slice operation e.g. from 01/Feb/90 to 06/Feb/90.
>>> stocks.ix['1990-Feb-01':'1990-Feb-06']
date AA GE IBM MSFT
date
1990-02-01 1990-02-01 4.98 2.87 16.79 0.51
1990-02-02 1990-02-02 5.04 2.87 16.89 0.51
1990-02-05 1990-02-05 5.07 2.87 17.32 0.51
1990-02-06 1990-02-06 5.01 2.88 17.56 0.51
>>>
Note: Above slice operation works only if the dates are in sorted order. If dates are not sorted then we need to
sort them first by using sort_index() command i.e. stocks.sort_index()
5.2.2 Resampling
Resampling is the conversion of time series from one frequency to another. If we convert higher frequency data
to lower frequency, then it is known as down-sampling; whereas if data is converted to low frequency to higher
frequency, then it is called up-sampling.
• Suppose, we want to see the data at the end of each month only (not on daily basis), then we can use
following resampling code,
54 PythonDSP
Chapter 5. Time series
• Pandas provides easier way to write the above code i.e. using ‘resampling’. Further, resampling provides
various features e.g. resample the data and show the mean value of the resampled data or maximum value
of the data etc., as shown below,
Downsampling
>>> # count total number of rows in each bin for each column
>>> stocks.resample('BM').count().head(3)
date AA GE IBM MSFT
date
1990-02-28 19 19 19 19 19
1990-03-30 22 22 22 22 22
1990-04-30 20 20 20 20 20
>>>
Upsampling
• When we upsample the data, the values are filled by NaN; therefore we need to use ‘fillna’ method to replace
the NaN value with some other values,as shown below,
In this section, we will plot various data from the DataFrame ‘stocks’ for various time ranges,
• First, plot the data of ‘AA’ for complete range,
56 PythonDSP
Chapter 5. Time series
• We can plot various data in the same window, by selecting the column using ‘ix’,
Pandas provide the ways to analyze the data over a sliding window e.g. in below code the data of ‘AA’ is plotted
aalong with the mean value over a window of length 250,
>>> stocks.AA.plot()
<matplotlib.axes._subplots.AxesSubplot object at 0xa9c5f4ec>
>>> stocks.AA.rolling(window=200,center=False).mean().plot()
<matplotlib.axes._subplots.AxesSubplot object at 0xa9c5f4ec>
>>> plt.show()
>>>
58 PythonDSP
Chapter 6
In previous chapters, we used only one or two files to read the data. In this chapter, multiple files are concatenated
to analyze the data.
In this section, various operations are performed on the various text-files to gather the useful information from it.
These text file contains the list to names of babies since 1880. Each record in the individual annual files has the
format “name,sex,number,” where name is 2 to 15 characters, sex is M (male) or F (female) and “number” is the
number of occurrences of the name. Each file is sorted first on sex and then on number of occurrences in descending
order. When there is a tie on the number of occurrences, names are listed in alphabetical order. Following is the
list of files on which various operations will be performed.
$ ls
yob1880.txt yob1882.txt yob1884.txt yob1886.txt
yob1881.txt yob1883.txt yob1885.txt yob1887.txt
$ head -n 10 yob1980.txt
Jennifer,F,58375
Amanda,F,35817
Jessica,F,33914
Melissa,F,31625
Sarah,F,25737
Heather,F,19965
Nicole,F,19910
Amy,F,19832
Elizabeth,F,19523
Michelle,F,19113
• First, we will read one file and then check to total number of rows in that file,
59
6.3. pivot_table
• Note that, the file contains 2000 rows; and each row contains a name and total number of babies with that
particular name along with the gender information. We can calculate the total number of boys and girls by
adding the ‘birthcount’ based on gender; i.e. we need to group the data based on gender and then add the
individual group’s birthcount,
>>> # total number of boys and girls in year 1880
>>> names1880.groupby('gender').birthcount.sum()
gender
F 90993
M 110493
Name: birthcount, dtype: int64
>>>
6.3 pivot_table
In previous chapters, we saw various examples of groupby and unstack operations. These two operations can be
performed by a single operation as well i.e. pivot_table. In this section, we will calculate the total number of
births in years 1880 to 1887 using pivot_table. For this first we need to merge the data from the files for these
year.
>>> years = range(1880, 1887)
>>> pieces = []
>>> columns = ['name', 'gender', 'birthcount']
>>> for year in years:
... path = 'yob{}.txt'.format(year)
... columns = ['name', 'gender', 'birthcount']
... for year in years:
... path = 'yob{}.txt'.format(year)
... df = pd.read_csv(path, names=columns)
... df['year']=year
... pieces.append(df)
... allData = pd.concat(pieces, ignore_index=True)
...
>>>
>>> len(allData)
105903
>>>
>>> allData.head(2)
name gender birthcount year
0 Mary F 7065 1880
1 Anna F 2604 1880
60 PythonDSP
Chapter 6. Reading multiple files
>>> total_births.plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot object at 0xa580b44c>
>>> plt.show()
>>>
• Next, we want to check the ratio of the names with total number of names. For this, we can write a function,
which calculates the ration and apply it to groupby option,
>>> # calculate ratio
... def add_prop(group):
... births = group.birthcount.astype(float)
... group['prop'] = births/births.sum() # add column prop
... return group
...
>>>
>>> names = allData.groupby(['year', 'gender']).apply(add_prop)
>>> names.head()
name gender birthcount year prop
0 Mary F 7065 1880 0.011092
1 Anna F 2604 1880 0.004088
(continues on next page)
62 PythonDSP