Comprehensive Guide Data Exploration Sas Using Python Numpy Scipy Matplotlib Pandas
Comprehensive Guide Data Exploration Sas Using Python Numpy Scipy Matplotlib Pandas
Introduction
Exploring data sets and developing deep understanding about the data is one of the most important skills
every data scientist should possess. People estimate that the time spent on these activities can go as high
as 80% of the project time in some cases.
Python has been gaining a lot of ground as preferred tool for data scientists lately, and for the right
reasons. Ease of learning, powerful libraries with integration of C/C++, production readiness and
integration with web stack are some of the main reasons for this move lately.
In this guide, I will use NumPy, Matplotlib, Seaborn, and Pandas to perform data exploration. These are
powerful libraries to perform data exploration in Python. The idea is to create a ready reference for some of
the regular operations required frequently. I am using an iPython Notebook to perform data exploration and
would recommend the same for its natural fit for exploratory analysis.
In case you missed it, I would suggest you to refer to the baby steps series of Python to understand the
basics of python programming.
Learning Python for data analysis – with instructions on installation and creating the environment
Libraries and data structures
Exploratory analysis in Python (using Pandas)
Data Munging in Python (using Pandas)
Here are the operations I’ll cover in this article (Refer to this article for similar operations in SAS):
Input data sets can be in various formats (.XLS, .TXT, .CSV, JSON ). In Python, it is easy to load data from
any source, due to its simple syntax and availability of predefined libraries, such as Pandas. Here I will
make use of Pandas itself.
Pandas features a number of functions for reading tabular data as a Pandas DataFrame object. Below are
the common functions that can be used to read data (including read_csv in Pandas):
Code
environment #Reading the dataset in a dataframe using Pandas print df.head(3) #Print first three observations
Output
Code df=pd.read_excel("E:/EMP.xlsx", "Data") # Load Data sheet of excel file EMP Output print df
Code:
df=pd.read_csv("E:/Test.txt",sep='\t') # Load Data from text file having tab '\t' delimeter print df
Output
Converting a variable data type to others is an important and common procedure we perform after loading
data. Let’s look at some of the commands to perform these conversions:
string_input to integer_outcome
The later operations are especially useful when you input value from user using raw_input(). By default, the
values are read at string.
There are multiple ways to do this. The simplest would be to use the datetime library and strptime
function. Here is the code:
from datetime import datetime char_date = 'Apr 1 2015 1:20 PM' #creating example character date date_obj =
Here, I want to transpose Table A into Table B on the variable Product. This task can be accomplished by
using Pandas dataframe.pivot:
Code
df=pd.read_excel("E:/transpose.xlsx", "Sheet1") # Load Data sheet of excel file EMP print df result=
Output
Sorting of data can be done using dataframe.sort(). It can be based on multiple variables and ascending or
descending both orders.
Code
Data visualization always helps to understand the data easily. Python has libraries like matplotlib and
seaborn to create multiple graphs effectively. Let’s look at the some of the visualizations to understand
below behavior of variable(s) .
Histogram:
Code
#Plot Histogram
df=pd.read_excel("E:/First.xlsx", "Sheet1")
#Plots in matplotlib reside within a figure object, use plt.figure to create new figure fig=plt.figure()
#Create one or more subplots using add_subplot, because you can't create blank figure ax =
fig.add_subplot(1,1,1)
#Variable ax.hist(df['Age'],bins = 5)
Output
Scatter plot:
Code
#Plots in matplotlib reside within a figure object, use plt.figure to create new figure fig=plt.figure()
#Create one or more subplots using add_subplot, because you can't create blank figure ax =
fig.add_subplot(1,1,1)
#Variable ax.scatter(df['Age'],df['Sales'])
#Labels and Tit plt.title('Sales and Age distribution') plt.xlabel('Age') plt.ylabel('Sales') plt.show()
Output
Box-plot:
Code
Output
Frequency Tables can be used to understand the distribution of a categorical variable or n categorical
variables using frequency tables.
Code
import pandas as pd
Output
Part 7: How to do sample Data set in Python?
To select sample of a data set, we will use library numpy and random. Sampling of data set always helps to
understand data quickly.
Let’s say, from EMP table, I want to select random sample of 5 employees.
Code
# get 5 random rows from the dataframe df dfr = df.ix[rindex] print dfr
Output
Code
Output
To understand the count, average and sum of variable, I would suggest you use dataframe.describe() with
Pandas groupby().
Code
Output
Part 10: How to recognize and Treat missing values and outliers in Pandas?
To identify missing values , we can use dataframe.isnull(). You can also refer article “Data Munging in
Python (using Pandas)“, here we have done a case study to recognize and treat missing and outlier values.
Code
Output
To treat missing values, there are various imputation methods available. You can refer these articles for
methods to detect Outlier and Missing values. Imputation methods for both missing and outlier values are
almost similar. Here we will discuss general case imputation methods to replace missing values. Let’s do it
using an example:
Code:
#Example to impute missing values in Age by the mean import numpy as np meanAge = np.mean(df.Age) #Using
numpy mean function to calculate the mean value df.Age = df.Age.fillna(meanAge) #replacing missing values in
the DataFrame
Part 11: How to merge / join data sets and Pandas dataframes?
Joining / merging is one of the common operation required to integrate datasets from different sources.
They can be handled effectively in Pandas using merge function:
Code:
df_new = pd.merge(df1, df2, how = 'inner', left_index = True, right_index = True) # merges df1 and df2 on
index # By changing how = 'outer', you can do outer join. # Similarly how = 'left' will do a left join # You
can also specify the columns to join instead of indexes, which are used by default.
End Notes:
In this comprehensive guide, we looked at the Python codes for various steps in data exploration and
munging. We also looked at the python libraries like Pandas, Numpy, Matplotlib and Seaborn to perform
these steps. In next article, I will reveal the codes to perform these steps in R.
Also See: If you have any doubts pertaining to Python, feel free to discuss with us.
Did you find the article useful? Do let us know your thoughts about this guide in the comments section
below.
If you like what you just read & want to continue your analytics
learning, subscribe to our emails, follow us on twitter or like
our facebook page.
Sunil Ray
I am a Business Analytics and Intelligence professional with deep experience in the Indian Insurance
industry. I have worked for various multi-national Insurance companies in last 7 years.