Docsity

Data analytics in python, Slides of Computer science

Partial preview of the text

Download Data analytics in python and more Slides Computer science in PDF only on Docsity!

INTRODUCTION TO PANDAS

UNIT- 1

Department of CSE, School of Engineering, Malla Reddy

Python

Pandas:

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

Pandas is defined as an open-source library that provides high-

performance data manipulation in Python. The name of Pandas is derived

from the word Panel Data , which means an Econometrics from

Multidimensional data. It is used for data analysis in Python and

developed by Wes McKinney in 2008.

Data analysis requires lots of processing, such as restructuring, cleaning or

merging , etc.

There are different tools are available for fast data processing, such as Numpy,

Scipy, Cython , and Panda. But we prefer Pandas because working with

Pandas is fast, simple and more expressive than other tools.

Pandas is the backbone for most of the data projects.

We can import the pandas library using the “import pandas”

command. We now have access to many pre-built classes and

Department of CSE, School of Engineering, Malla Reddy

PYTHON-PANDAS UNIT-I

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

Data Representation:

It represents the data in a form that is suited for data analysis through

its DataFrame and Series.

Clear code:

The clear API of the Pandas allows you to focus on the core part of the

code. So, it

provides clear and concise code for the user.

Benefits of

Pandas:

In order to be able to work with the data in Python, we’ll need to read the data (csv,

excel, dictionary...) file into a Pandas Data.frame.

A DataFrame is a way to represent and work with tabular data.

Tabular data has rows and columns , just like our csv file. In order to read in the data, we ll‟

need to use pandas.read_csv function. This function will take in a csv file and return a

DataFrame.

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

The Pandas provides two data structures for processing the data, i.e.,

**1. Series

  1. DataFrame**

1) Series

It is defined as a one-dimensional array that is capable of storing

various data types. The row labels of series are called the index.

We can easily convert the list, tuple, and dictionary into series

using “Series' method.

A Series cannot contain multiple columns.

It has a parameter i.e Data: It can be any list, dictionary, or scalar

value.

Creating Series from Array:

Before creating a Series, Firstly, we have to import the numpy

Pandas Data

Structure:

Department of CSE, School of Engineering, Malla Reddy

PYTHON-PANDAS UNIT-I

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

import pandas as pd

import numpy as np

info = np.array(['P','a','n','d','a','s'])

a = pd.Series(info)

print(a)

Output:

0 P

1 a

2 n

3 d

4 a

5 s

dtype: object

Example-2:

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

import pandas as pd

import numpy as np

mytuple = ("apple", "banana", "cherry")

print(mytuple)

ts=pd.Series ( mytuple)

print(a)

Output:

Example-3:

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

pandas.Series(data=None, index=None, dtype=None, name=None,

copy=False, fastpath=False)

Parameters:

data: array- Contains data stored in Series.

index: array-like or Index (1d)

dtype: str, numpy. dtype, or Extension Dtype, optional

name: str, optional

copy: bool, default False

Series syntax :

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

1. Count: Return number of non-NA/null observations in the

Series.

s = pd.Series([0.0, 1.0, np.nan])

s.count()

2. size: Return the number of elements in the underlying data.

s.size()

3. pop: Return item and drops from series. Raise KeyError if not

found.

s.pop(0)

Series functions :

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

It is a widely used data structure of pandas and works with a two-

dimensional array with labelled axes (rows and columns). DataFrame is

defined as a standard way to store data and has two different indexes, i.e.,

row index and column index. It consists of the following properties:

The columns can be heterogeneous types like int, bool, and so on.

It can be seen as a dictionary of Series structure where both the

rows and columns are

indexed. It is denoted as "columns" in case of columns and "index" in

case of rows.

Create a DataFrame using List:

We can easily create a DataFrame in Pandas using list.

import pandas as pd

a list of strings

x = ['Python','Pandas']

Python Pandas

DataFrame:

Output:

0 python

1 pandas

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

pandas.DataFrame(data=None, index=None, columns=None, dtype=None,

copy=None)

Data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame

Dict can contain Series, arrays, constants, dataclass or list-like objects. If

data is a dict, column order follows insertion-order. If a dict contains Series

which have an index defined, it is aligned by its index.

Index: Index to use for resulting frame. Will default to Range Index if no indexing

information part of input data and no index provided.

Column : labels to use for resulting frame when data does not have them, defaulting

to Range Index(0, 1, 2, …, n). If data contains column labels, will perform column

selection instead.

Data type : Data type to force. Only a single dtype is allowed. If None, infer.

Data Frame syntax :

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

Pandas is a very powerful and popular framework for data

analysis and manipulation.

One of the most striking features of Pandas is its ability to read and write

various types of files including CSV and Excel.

You can effectively and easily manipulate CSV files in Pandas using

functions like read_csv() and to_csv().

Installing Pandas

We have to install Pandas before using it. Let's use pip in Jupyter

notebook

Reading and Writing CSV Files

using Pandas:

pip install

pandas

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

How to read the csv file using pandas:

Once the pandas library is imported by using import statement with

out any error.

That assumes the library is installed. Then we can load a csv

file using the pandas built-in function “ pandas.read_csv() ”

We simply type the word pandas (or) object of pandas , then a dot

and name of the read_csv() function with arguments (or ) with out

arguments.

Reading CSV Files with

read_csv():

Import pandas as pd

df=pd.read_csv(“path of file, where it is

located”)

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

import pandas as pd

df=pd.read_excel(r"C:\Users\Documents\R programs\data.xlsx")

df.head( 5 )

Output:

Example for read the EXCEL file

using pandas :

Department of CSE, School of Engineering, Malla Reddy

Middle Level

Language

Structured

Language

Rich

Library

Extensible

Recursion

Pointers

Speed

Memory

Management

DataFrames are tabular. Turning a DataFrame into a CSV file is as simple

by using to_csv(“location of the path).

When writing a DataFrame to a CSV file, you can also change the

column names, using the columns argument , or specify a delimiter via

the sep argument. If you don't specify either of these , you'll end up with a

standard Comma-Separated Value file.

Example:

import pandas as pd

cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida']],

columns=['City', 'State'])

cities.to_csv(r'C:\Users\Desktop\new\cities.csv')

Output: after executing check new folder on the desktop, then find out the

cities.csv file

Writing CSV Files with

to_csv() :

Department of CSE, School of Engineering, Malla Reddy