0% found this document useful (0 votes)
3 views43 pages

LC - Python Pandas

Uploaded by

aayushibnk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

LC - Python Pandas

Uploaded by

aayushibnk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Handling

using Pandas
Informatics Practices

Debasree Sarkar 1
Data Handling using Pandas -1
Python Library – Matplotlib
Matplotlib is a comprehensive library for creating static, animated,
and interactive visualizations in [Link] is used to create
1. Develop publication quality plots with just a few lines of code
2. Use interactive figures that can zoom, pan, update...
We can customize and Take full control of line styles, font properties,
axes properties... as well as export and embed to a number of file
formats and interactive environments

Debasree Sarkar 2
Data Handling using
Pandas -1
Python Library – Pandas
It is a most famous Python package for data science, which offers
powerful and flexible data structures that make data analysis and
manipulation [Link] makes data importing and data analyzing
much easier. Pandas builds on packages like NumPy and matplotlib
to give us a single & convenient place for data analysis and
visualization work.

Debasree Sarkar 3
Data Handling using
Pandas -1
Basic Features of Pandas
1. Dataframe object help a lot in keeping track of our data.
2. With a pandas dataframe, we can have different data types (float, int,
string, datetime, etc) all in one place
3. Pandas has built in functionality for like easy grouping & easy joins
of data, rolling windows
4. Good IO capabilities; Easily pull data from a MySQL database
directly into a data frame
5. With pandas, you can use patsy for R-style syntax in
doing regressions.
6. Tools for loading data into in-memory data objects from
different file formats.
7. Data alignment and integrated handling of missing data.
8. Reshaping and pivoting of data sets.
9. Label-based slicing, indexing and Debasree subsetting
Sarkar of large data sets. 4
Pandas – Installation/Environment Setup
Pandas module doesn't come bundled with Standard Python.
If we install Anaconda Python package Pandas will be
installed by default.
Steps for Anaconda installation & Use
1. visit the site [Link]
2. Download appropriate anaconda installer
3. After download install it.
4. During installation check for set path and all user
5. After installation start spyder utility of anaconda from start menu
6. Type import pandas as pd in left pane([Link])
7. Then run it.
8. If no error is show then it shows pandas is installed.
9. Like default [Link] we can create another .py file from new
window option of file menu for new program.
Debasree Sarkar 5
Data Handling using
Pandas -1 Pandas – Installation/Environment Setup

Pandas installation can be done in Standard Python


distribution,using following steps.
1. There must be service pack installed on our computer if we
are using [Link] it is not installed then we will not be
able to install pandas in existing Standard Python(which is
already installed).So install it first(google it).
2. We can check it through properties option of my computer
icon.

3. Now install latest version(any one above 3.4) of python.


Debasree Sarkar 6
Pandas – Installation/Environment Setup

4. Now move to script folder of python distribution in command


prompt (through cmd command of windows).
5. Execute following commands in command prompt serially.
>pip install numpy
>pip install six
>pip install pandas
Wait after each command for installation
Now we will be able to use pandas in standard python
distribution.
6. Type import pandas as pd in python (IDLE) shell.
7. If it executed without error(it means pandas is installed on
your system)
Debasree Sarkar 7
Data Structures in Pandas
Two important data structures of pandas are–Series,DataFrame
1. Series
Series is like a one-dimensional array like structure with
homogeneous data. For example, the following series is a
collection of integers.

Basic feature of series are


❖ Homogeneous data
❖ Size Immutable
❖ Values of Data Mutable
Debasree Sarkar 8
2. DataFrame
DataFrame is like a two-dimensional array with
heterogeneous data.
SR. Admn Student Name Class Section Gender Date Of
No. No Birth
1 001284 NIDHI MANDAL I A Girl 07/08/2010
2 001285 SOUMYADIP I A Boy 24/02/2011
BHATTACHARYA
3 001286 SHREYAANG I A Boy 29/12/2010
SHANDILYA
Basic feature of DataFrame are
❖ Heterogeneous data
❖ Size Mutable
❖ Data Mutable
Debasree Sarkar 9
Pandas Series
It is like one-dimensional array capable of holding data
of any type (integer, string, float, python objects, etc.).
Series can be created using constructor.
Syntax :- [Link]( data, index, dtype, copy)
Creation of Series is also possible from – ndarray,
dictionary, scalar value.
Series can be created using
1. Array
2. Dict
3. Scalar value or constant

Debasree Sarkar 10
Pandas Series

Create an Empty Series

e.g.

import pandas as pseries


s = [Link]()
print(s)

Output
Series([], dtype: float64)
Debasree Sarkar 11
Pandas Series
Create a Series from ndarray
Without index With index position
e.g. e.g.

import pandas as pd1 import pandas as p1


import numpy as np1 import numpy as np1
data = [Link](['a','b','c','d']) data = [Link](['a','b','c','d'])
s = [Link](data) s = [Link](data,index=[100,101,102,103])
print(s) print(s)

Output Output
1 a 100 a
2 b 101 b
3 c 102c 103d
4 d dtype:
dtype: object object
Note : default index is starting
from 0 Note : index is starting from 100
Debasree Sarkar 12
Pandas Series
Create a Series from dict
Eg.1(without index) Eg.2 (with index)
import pandas as pd1 import pandas as pd1
import numpy as np1 import numpy as np1
data = {'a' : 0., 'b' : 1., 'c' : 2.} data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = [Link](data) s = [Link](data,index=['b','c','d','a'])
print(s) print(s)

Output Output
a 0.0 b 1.0
b 1.0 c 2.0
c 2.0 d NaN
dtype: float64 a 0.0
dtype: float64

Debasree Sarkar 13
Create a Series from Scalar
e.g
import pandas as pd1
import numpy as np1
s = [Link](5, index=[0, 1, 2, 3])
print(s)
Output
0 5
1 5
2 5
3 5
dtype: int64
Note :- here 5 is repeated for 4 times (as per no of index)
Debasree Sarkar 14
Pandas Series
Maths operations with Series
e.g.
import pandas as pd1
s = [Link]([1,2,3])
t = [Link]([1,2,4])
u=s+t #addition operation print (u) 0 2
1 4
u=s*t # multiplication operation 2 7
dtype: int64
print (u) output
0 1
1 4
2 12
dtype: int64

Debasree Sarkar 15
Pandas Series
Head function
e.g

import pandas as pd1


s = [Link]([1,2,3,4,5],index = ['a','b','c','d','e'])
print ([Link](3))

Output
a 1
b. 2
c. 3
dtype: int64
Return first 3 elements
Debasree Sarkar 16
Pandas Series
tail function
e.g

import pandas as pd1


s = [Link]([1,2,3,4,5],index = ['a','b','c','d','e'])
print ([Link](3))

Output
c 3
d. 4
e. 5
dtype: int64
Return last 3 elements
Debasree Sarkar 17
Accessing Data from Series with indexing and slicing
e.g.
import pandas as pd1
s = [Link]([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s[0])# for 0 index position
print (s[:3]) #for first 3 index values
print (s[-3:]) # slicing for last 3 index values
Output
1
a. 1
b. 2
c. 3
dtype: int64 c 3
d. 4
e. 5
dtype: int64

Debasree Sarkar 18
Pandas Series
Retrieve Data Using Label as (Index)
e.g.

import pandas as pd1


s = [Link]([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s[['c','d']])

Output c
3
d 4
dtype: int64

Debasree Sarkar 19
Pandas Series
Retrieve Data from selection
There are three methods for data selection:
▪ loc gets rows (or columns) with particular labels from
the index.
▪ iloc gets rows (or columns) at particular positions in
the index (so it only takes integers).
▪ ix usually tries to behave like loc but falls back to
behaving like iloc if a label is not present in the index.
ix is deprecated and the use of loc and iloc is encouraged
instead

Debasree Sarkar 20
Pandas Series
Retrieve Data from
selection
e.g. >>> [Link][:3] # the integer is in the index so
>>> s = [Link]([Link],
index=[49,48,47,46,45, 1, 2, 3, 4, 5]) [Link][:3] works like loc
>>> [Link][:3] # slice the first three rows 49 NaN
49 NaN 48 NaN
48 NaN
47 NaN 47 NaN
>>> [Link][:3] # slice up to and including 46 NaN
label 3 45 NaN
49 NaN
48 NaN
1 NaN
47 NaN 2 NaN
46 NaN 3 NaN
45 NaN
1 NaN
2 NaN
3 NaN
Debasree Sarkar 21
Data Handling using Pandas -1

Pandas DataFrame
It is a two-dimensional data structure, just like any table
(with rows & columns).
Basic Features of DataFrame
❑ Columns may be of different types
❑ Size can be changed(Mutable)
❑ Labeled axes (rows / columns)
❑ Arithmetic operations on rows and columns
Structure

Rows

It can be created using constructor


[Link]( data, index, columns, dtype, copy)
Debasree Sarkar 22
Data Handling using
Pandas DataFrame
Pandas -1 Create DataFrame
It can be created with followings
❑ Lists
❑ dict
❑ Series
❑ Numpy ndarrays
❑ Another DataFrame

Create an Empty DataFrame


e.g.
import pandas as pd1 Empty
df1 = [Link]() output DataFrame
Columns: [ ]
print(df1) Index: [ ]
Debasree Sarkar 23
Pandas DataFrame
Create a DataFrame from Lists 0
e.g.1 0 1
output 1 2
import pandas as pd1 2 3
data1 = [1,2,3,4,5] 3 4
df1 = [Link](data1) 4 5

print (df1)
e.g.2
import pandas as pd1
data1 = [['Freya',10],['Mohak',12],['Dwivedi',13]]
Name Age
df1 = [Link](data1,columns=['Name','Age'])
1 Freya 10
print (df1) output 2 Mohak 12
2 Dwivedi 13

Write below for numeric value as float


df1 = [Link](data,columns=['Name','Age'],dtype=float)
Debasree Sarkar 24
Pandas DataFrame
Create a DataFrame from Dict of ndarrays / Lists
e.g.1
import pandas as pd1
data1 = {'Name':['Freya', 'Mohak'],'Age':[9,10]}
df1 = [Link](data1)
print (df1)
Output
Name Age
1 Freya 9
2 Mohak 10
Write below as 3rd statement in above prog for indexing
df1 = [Link](data1, index=['rank1','rank2','rank3','rank4'])
Debasree Sarkar 25
Pandas DataFrame
Create a DataFrame from List of Dicts
e.g.1
import pandas as pd1
data1 = [{'x': 1, 'y': 2},{'x': 5, 'y': 4, 'z':5}]
df1 = [Link](data1)
print (df1)
Output
x y z
0 1 2 NaN
1 5 4 5.0

Write below as 3rd stmnt in above program forindexing


df = [Link](data, index=['first', 'second'])

Debasree Sarkar 26
Pandas DataFrame
Create a DataFrame from Dict of Series
e.g.1
import pandas as pd1
d1 = {'one' : [Link]([1, 2, 3], index=['a', 'b', 'c']),
'two' : [Link]([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = [Link](d1)
print (df1)
Output
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
Column Selection -> print (df ['one'])
Adding a new column by passing as Series: ->
df1['three']=[Link]([10,20,30],index=['a','b','c'])
Adding a new column using the existing columns values
df1['four']=df1['one']+df1['three']
Debasree Sarkar 27
Create a DataFrame from .txt file
Having a text file './inputs/[Link]' as:
1 1 12.92
1 2 90.75
1 3 60.90
2 1 71.34
Pandas is shipped with built-in reader methods. For example the
pandas.read_table method seems to be a good way to read (also in chunks)
a tabular data file.
import pandas
df = pandas.read_table('./input/[Link]', delim_whitespace=True,
names=('A', 'B', 'C'))
will create a DataFrame objects with column named Amade of data of type
int64, B of int64 and C of float64
Debasree Sarkar 28
Create a DataFrame from csv(comma separated value) file / import data
from cvs file
e.g.
Suppose [Link] file contains following data
Date,"price","factor_1","factor_2"
2012-06-11,1600.20,1.255,1.548
2012-06-12,1610.02,1.258,1.554
import pandas as pd
# Read data from file '[Link]'
# (in the same directory that your python program is based)
# Control delimiters, rows, column names with read_csv
data = pd.read_csv("[Link]")
# Preview the first 1 line of the loaded data
[Link](1)
Debasree Sarkar 29
Pandas DataFrame
Column addition
df = [Link]({"A": [1, 2, 3], "B": [4, 5, 6]})
c = [7,8,9]
df[‘C'] = c

Column Deletion
del df1['one'] # Deleting the first column using DEL function
[Link]('two') #Deleting another column using POP function
Rename columns
df = [Link]({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> [Link](columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
Debasree Sarkar 30
Pandas DataFrame
Row Selection, Addition, and Deletion
#Selection by Label
import pandas as pd1
d1 = {'one' : [Link]([1, 2, 3], index=['a', 'b', 'c']),
'two' : [Link]([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df1
= [Link](d1)
print ([Link]['b'])
Output
one 2.0
two 2.0
Name: b, dtype: float64

Debasree Sarkar 31
Pandas DataFrame
#Selection by integer location
import pandas as pd1
d1 = {'one' : [Link]([1, 2, 3], index=['a', 'b','c']),
'two' : [Link]([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = [Link](d1)
print ([Link][2])

Output
one 3.0
two 3.0
Name: c, dtype: float64

Slice Rows : Multiple rows can be selected using ‘ : ’operator.


print (df1[2:4])
Debasree Sarkar 32
Pandas DataFrame
Addition of Rows
import pandas as pd1

df1 = [Link]([[1, 2], [3, 4]], columns = ['a','b'])


df2 = [Link]([[5, 6], [7, 8]], columns = ['a','b'])

df1 = [Link](df2)
print (df1)

Deletion of Rows
# Drop rows with label 0
df1 = [Link](0)

Debasree Sarkar 33
Pandas DataFrame
Iterate over rows in a dataframe
e.g.
import pandas as pd1
import numpy as np1
raw_data1 = {'name': ['freya', 'mohak'],
'age': [10, 1],
'favorite_color': ['pink', 'blue'],
'grade': [88, 92]}
df1 = [Link](raw_data1, columns = ['name', 'age',
'favorite_color', 'grade'])
for index, row in [Link]():
print (row["name"], row["age"])

Output
freya 10
mohak 1
Debasree Sarkar 34
Pandas DataFrame
Head & Tail
head() returns the first n rows (observe the index values). The default number of
elements to display is five, but you may pass a custom number. tail() returns the
last n rows .e.g.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':[Link](['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
'Age':[Link]([25,26,25,23,30,29,23]),
'Rating':[Link]([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = [Link](d)
print ("Our data frame is:")
print df
print ("The first two rows of the data frame is:")
print [Link](2)
Debasree Sarkar 35
Pandas DataFrame
Indexing a DataFrame using .loc[ ] :
This function selects data by the label of the rows and columns.
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np

df = [Link]([Link](8, 4),
index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D'])

#select all rows for a specific column


print [Link][:,'A']
Debasree Sarkar 36
Python Pandas
Pandas DataFrame
Accessing a DataFrame with a boolean index :
In order to access a dataframe with a boolean index, we have to create a
dataframe in which index of dataframe contains a boolean value that is “True”
or “False”.
# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':[“Mohak", “Freya", “Roshni"],
'degree': ["MBA", "BCA", "[Link]"],
'score':[90, 40, 80]}

# creating a dataframe with boolean index


df = [Link](dict, index = [True, False, True])
# accessing a dataframe using .loc[] function
print([Link][True]) #it will return rows of Mohak and Roshni only(matching true only)
Debasree Sarkar 37
Python Pandas

• Pandas DataFrame
• Binary operation over dataframe with series e.g.
• import pandas as pd
• x = [Link]({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
• y = [Link]([1, 2, 3]) new_x =
[Link](y, axis=0) print(new_x)

• Output
0 1 2
0 1 4 7
1 4 10 16
2 9 18 27
Debasree Sarkar 38
Pandas DataFrame
Binary operation over
dataframe with dataframe
import pandas as pd
x = [Link]({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
y = [Link]({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
new_x = [Link](y, axis=0)
print(new_x)
Output
0 1 2
0 2 8 14
1 4 10 16
2 6 12 18
Note :- similarly we can use sub,mul,div functions
Debasree Sarkar 39
Pandas DataFrame
Merging/joining dataframe
e.g.
import pandas as pd
left = [Link]({
'id':[1,2],
'Name': ['anil', 'vishal'],
'subject_id':['sub1','sub2']})
right = [Link](
{'id':[1,2],
'Name': ['sumer', 'salil'],
'subject_id':['sub2','sub4']})
print ([Link](left,right,on='id'))
Output
id Name_x subject_id_x Name_y subject_id_y
0 1 Anil sub1 Sumer sub2
1 2 Vishal sub2 Salil sub4
Debasree Sarkar 40
Pandas DataFrame
Merging/combining dataframe(different styles)

[Link](left, right, on='subject_id', how='left') #left join


[Link](left, right, on='subject_id', how='right') #right join
[Link](left, right, how='outer', on='subject_id') #outer join
[Link](left, right, on='subject_id', how='inner') # innerjoin

Debasree Sarkar 41
Concate two DataFrame objects with identical
columns.
df1 = [Link]([['a', 1], ['b', 2]],
... columns=['letter', 'number'])
>>> df1
letter number
0 a. 1
1 b. 2
>>> df2 = [Link]([['c', 3], ['d', 4]],
... columns=['letter', 'number'])
>>> df2
letter number
0 c. 3
1 d. 4
>>> [Link]([df1, df2])
letter number
1 a 1
2 b 2
3 c 3
4 d 4
Debasree Sarkar 42
Data Handling using Pandas -1
Export Pandas DataFrame to a CSV File
e.g.
import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],


'Price': [22000,25000,27000,35000]
}

df = [Link](cars, columns= ['Brand', 'Price'])

df.to_csv (r'C:\export_dataframe.csv', index = False, header=True)

print (df)

Debasree Sarkar 43

You might also like