The Wayback Machine - https://web.archive.org/web/20240531122017/https://www.geeksforgeeks.org/exploratory-data-analysis-in-python-set-2/
Open In App

Exploratory Data Analysis in Python | Set 2

Last Updated : 21 Jan, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article, we have discussed some basic techniques to analyze the data, now let’s see the visual techniques.

Let’s see the basic techniques –




# Loading Libraries
  
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import trim_mean
  
# Loading Data
data = pd.read_csv("state.csv")
   
# Check the type of data
print ("Type : ", type(data), "\n\n")
   
# Printing Top 10 Records
print ("Head -- \n", data.head(10))
   
# Printing last 10 Records 
print ("\n\n Tail -- \n", data.tail(10))
  
# Adding a new column with derived data  
data['PopulationInMillions'] = data['Population']/1000000
   
# Changed data
print (data.head(5))
  
# Rename column heading as it 
# has '.' in it which will create
# problems when dealing functions 
   
data.rename(columns ={'Murder.Rate': 'MurderRate'},
                                    inplace = True)
   
# Lets check the column headings
list(data)


Output :

Type : class 'pandas.core.frame.DataFrame'


Head -- 
          State  Population  Murder.Rate Abbreviation
0      Alabama     4779736          5.7           AL
1       Alaska      710231          5.6           AK
2      Arizona     6392017          4.7           AZ
3     Arkansas     2915918          5.6           AR
4   California    37253956          4.4           CA
5     Colorado     5029196          2.8           CO
6  Connecticut     3574097          2.4           CT
7     Delaware      897934          5.8           DE
8      Florida    18801310          5.8           FL
9      Georgia     9687653          5.7           GA


 Tail -- 
             State  Population  Murder.Rate Abbreviation
40   South Dakota      814180          2.3           SD
41      Tennessee     6346105          5.7           TN
42          Texas    25145561          4.4           TX
43           Utah     2763885          2.3           UT
44        Vermont      625741          1.6           VT
45       Virginia     8001024          4.1           VA
46     Washington     6724540          2.5           WA
47  West Virginia     1852994          4.0           WV
48      Wisconsin     5686986          2.9           WI
49        Wyoming      563626          2.7           WY


        State  Population  Murder.Rate Abbreviation  PopulationInMillions
0     Alabama     4779736          5.7           AL              4.779736
1      Alaska      710231          5.6           AK              0.710231
2     Arizona     6392017          4.7           AZ              6.392017
3    Arkansas     2915918          5.6           AR              2.915918
4  California    37253956          4.4           CA             37.253956


['State', 'Population', 'MurderRate', 'Abbreviation']

Visualizing Population per Million




# Plot Population In Millions
fig, ax1 = plt.subplots()
fig.set_size_inches(15,  9)
  
  
ax1 = sns.barplot(x ="State", y ="Population", 
                  data = data.sort_values('MurderRate'), 
                                        palette ="Set2")
  
ax1.set(xlabel ='States', ylabel ='Population In Millions')
ax1.set_title('Population in Millions by State', size = 20)
  
plt.xticks(rotation =-90)


Output:

(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
 a list of 50 Text xticklabel objects)

Visualizing Murder Rate per Lakh




# Plot Murder Rate per 1, 00, 000
  
fig, ax2 = plt.subplots()
fig.set_size_inches(15,  9)
  
  
ax2 = sns.barplot(
    x ="State", y ="MurderRate", 
    data = data.sort_values('MurderRate', ascending = 1), 
                                         palette ="husl")
  
ax2.set(xlabel ='States', ylabel ='Murder Rate per 100000')
ax2.set_title('Murder Rate by State', size = 20)
  
plt.xticks(rotation =-90)


Output :

(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
 a list of 50 Text xticklabel objects)


Although Louisiana is ranked 17 by population (about 4.53M), it has the highest Murder rate of 10.3 per 1M people.

Code #1 : Standard Deviation




Population_std = data.Population.std()
print ("Population std : ", Population_std)
  
MurderRate_std = data.MurderRate.std()
print ("\nMurderRate std : ", MurderRate_std)


Output :

Population std :  6848235.347401142

MurderRate std :  1.915736124302923

Code #2 : Variance




Population_var = data.Population.var()
print ("Population var : ", Population_var)
  
MurderRate_var = data.MurderRate.var()
print ("\nMurderRate var : ", MurderRate_var)


Output :

Population var :  46898327373394.445

MurderRate var :  3.670044897959184

Code #3 : Inter Quartile Range




# Inter Quartile Range of Population
population_IQR = data.Population.describe()['75 %'] - 
                 data.Population.describe()['25 %']
  
print ("Population IQR : ", population_IRQ)
  
# Inter Quartile Range of Murder Rate
MurderRate_IQR = data.MurderRate.describe()['75 %'] - 
                 data.MurderRate.describe()['25 %']
  
print ("\nMurderRate IQR : ", MurderRate_IQR)


Output :

Population IQR :  4847308.0

MurderRate IQR :  3.124999999999999

Code #4 : Median Absolute Deviation (MAD)




Population_mad = data.Population.mad()
print ("Population mad : ", Population_mad)
  
MurderRate_mad = data.MurderRate.mad()
print ("\nMurderRate mad : ", MurderRate_mad)


Output :

Population mad :  4450933.356000001

MurderRate mad :  1.5526400000000005


Similar Reads

Exploratory Data Analysis in Python | Set 1
Exploratory Data Analysis is a technique to analyze data with visual techniques and all statistical results. We will learn about how to apply these techniques before applying any Machine Learning Models. Loading Libraries: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import trim_mean
3 min read
Exploratory Data Analysis on Iris Dataset
In this article, we will discuss how to perform Exploratory Data Analysis on the Iris dataset. Before continuing with this article, we have used two terns i.e. EDA and Iris Dataset. Let's see a brief about these datasets. What is Exploratory Data Analysis?Exploratory Data Analysis (EDA) is a technique to analyze data using some visual Techniques. W
9 min read
Exploratory Data Analysis in R Programming
Exploratory Data Analysis or EDA is a statistical approach or technique for analyzing data sets to summarize their important and main characteristics generally by using some visual aids. The EDA approach can be used to gather knowledge about the following aspects of data. Main characteristics or features of the data.The variables and their relation
12 min read
Exploratory Data Analysis (EDA) - Types and Tools
Exploratory data analysis was promoted by John Tukey to encourage statisticians to explore data, and possibly formulate hypotheses that might cause new data collection and experiments. EDA focuses more narrowly on checking assumptions required for model fitting and hypothesis testing. It also checks while handling missing values and making transfor
6 min read
What is Exploratory Data Analysis?
Exploratory data analysis is one of the basic and essential steps of a data science project. A data scientist involves almost 70% of his work in doing the EDA of the dataset. In this article, we will discuss what is Exploratory Data Analysis (EDA) and the steps to perform EDA. What is Exploratory Data Analysis (EDA)?Exploratory Data Analysis (EDA)
14 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Difference Between Factor Analysis and Principal Component Analysis
Factor Analysis (FA) and Principal Component Analysis (PCA) are two pivotal techniques used for data reduction and structure detection. Despite their similarities, they serve distinct purposes and operate under different assumptions. This article explores the key differences between FA and PCA. Understanding Principal Component Analysis (PCA)Princi
4 min read
Data Analysis and Visualization with Python | Set 2
Prerequisites : NumPy in Python, Data Analysis Visualization with Python Python is very well known for Data analysis and visualizations because of the vast libraries it provides such as Pandas, Numpy, Matplotlib, etc. Today we will learn some methods to understand our data better and to gain some useful insights from it. 1. Storing DataFrame in CSV
5 min read
Different Sources of Data for Data Analysis
Data collection is the process of acquiring, collecting, extracting, and storing the voluminous amount of data which may be in the structured or unstructured form like text, video, audio, XML files, records, or other image files used in later stages of data analysis. In the process of big data analysis, “Data collection” is the initial step before
5 min read