Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python

Uploaded by

aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python

Uploaded by

aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

🐍

Python
Shortcuts for jupyter notebook

Shortcuts Functionality

ctrl + enter or shift + enter Run the program

x (not ctrl+x) Cut

v paste

c copy

z undo

a Insert an empty cell above

b Insert an empty cell below

d, d (press d and d twice) delete the cell

y For converting markdown to code

opens all shortcuts

toggle the output

shift + L For showing numbers on each line of code

Markdown cell
A cell that contains strictly documentation and it would never be executed.

Datatypes in python
int - Refers to the integer
float - Refers to the floating point number or decimal
bool - This is boolean - ‘True’ or ‘False’ value
string - Text values composed of sequence of characters

💡 You can’t concatenate one datatype with another

Python 1
Typecasting
Converting from one datatype to other

x = 5
type(x)

int

float(x)

5.0

For finding the type of the variable

type(var)

Updating values in python

z = 1
z = 6
z

Comments

# This is a comment that starts with hashtag

New line
Just use a backslash, forward slash is divide so can’t use

Python 2
5*2 \
+3

13

Indexing elements

#suppose you have to extract a particular element from a s


"Saturday"[3]

"u"

Operators

Arithmetic operators

Operator

+ Addition

- Subtraction

* Multiplication

** Power

% Remainder

Comparison Operators

Operator name Sign

Equal to ==

Not equal to !=

Greater than or equal to >=

Less than or equal to <=

Greater than >

Less than <

Logical Operators or Boolean Operators

Python 3
Operators Usage

True and True =


When both the conditions need to be True; True and False
and
true = False; False and
False = False

True or True = True;


When one of the conditions need to True or False = True;
or
be true False or False =
False

not True = False; not


not Leads to opposite of statement
False = True

Priority of operators -

1. not

2. and

3. or

Identity Operators

Operator Meaning

is ==

is not !=

💡 1. Python is case sensitive, so keep the syntax in mind where it’s


capital and where it’s small letter

Conditional statements

1st type

if condition:
conditional code

else:
else code

Python 4
2nd type

if condition:
conditional code

if condition:
conditional code

3rd type

if condition:
condition code

elif condition:
condition code

else:
condition code

Main difference

Feature if-elif if if

Conditions are mutually


Dependency Conditions are independent.
exclusive.

Execution Executes one block only. Executes all true blocks.

Stops checking after one Checks all conditions, even if


Performance
condition is true. one is true.

Handle multiple true


Use Case Choose one path to execute.
conditions.

Functions

1. Function without parameters

Defining function

Python 5
def function_name():
function body

Function calling - When we have to use that function

function_name()

Eg without parameter

def aditya():
print("He is great")

aditya()

He is great

2. Function with parameters

Defining function

def function_name(parameter):
function body

Function calling

function_name(argument)

Eg

def plus_two(x):
return x+10

Python 6
plus_two(4)

14

3. print() vs return

Main difference

1. print()
Purpose: It displays something on the screen.

Usage: Used when you want to show information to the user


(e.g., results, messages).

Example:

python
Copy code
def say_hello():
print("Hello, Aditya!")

say_hello()

Copy code
Hello, Aditya!

print() doesn't give anything back to the program; it just shows


the message. Once printed, you can't "use" the value again in
your code.

2. return

Python 7
Purpose: It sends a value back to the part of the code where
the function was called.

Usage: Used when you want to use the result later in your
program.

Example:

python
Copy code
def add_numbers(a, b):
return a + b

result = add_numbers(5, 3)
print(result)

The return statement doesn't show anything on the screen by


itself, but it allows the program to store or use the result ( 8
here).

Key Difference
print: Outputs something for the user to see but doesn't allow
the program to use that output.

return : Gives a result to the program for further use but doesn't
display it unless you explicitly print it.

Why both are useful


print()is like talking: You are saying something to the outside
world (the user).

returnis like handing over a result: You are giving something


back for the program to continue its work.

Extra note

Python 8
💡 We can return only a single result out of function

def plus_ten(a):
result = a*10
return "Outcome"
return result

plus_ten(3)

'Outcome'

def plus_ten(a):
result = a*10
print("Outcome")
return result

plus_ten(3)

Outcome
30

4. Function within function


Make one function, it will return some value and that value can be used
for the second function. But remember, their parameters should be
same only then the function will be able to execute.
Ex.

Python 9
def wage(hours):
return hours*10

def with_bonus(hours):
return wage(hours)+50

wage(10), with_bonus(10)

(100, 150)

5. Combining conditional statement and function


The function takes money from the user. If the saving is equal to or
more than $100 then it returns with an extra $10 otherwise give an
statment

def add_money(m):
if m>=100:
m = m+10
return m
else:
return "Save more, man!"

add_money(90)

'Save more, man!'

6. Creating functions with few arguments

def parameters(a,b,c):
result = a-b*c
print("Parameter a equals to ", a)
print("Parameter b equals to ", b)
print("Parameter c equals to ", c)
return result

Python 10
parameters(b=2,c=3,a=10)

Parameter a equals to 10
Parameter b equals to 2
Parameter c equals to 3
4

7. Built-In functions

1. type() : Obtains the type of variable you use as an argument

2. int() , float() , str() : Converts the argument into integer, float


and string type, respectively only if it’s possible

3. max() : Returns the highest value in the function. Ex. max(10,20,30)


—> 30

4. min() : Returns the lowest value of the argument

5. abs() : Returns the absolute value of its argument. Ex. abs(-20) —>
20

6. sum() : Calculates the sum of all elements in the list designated as


an argument

7. round(x,y) : Returns the float of its argument (x), rounded to


specified number of digits (y) after the decimal point. Ex.
round(14.5678, 2) —> 14.57

8. : Returns x to the power of y. Same as ‘**’ this operator. Ex.


pow(x,y)

pow(10,2) —> 100

9. len() : Returns the length of the string and not for numbers. It can
even count the number of elements in list. Ex. len(”power”) —> 5

Storing Data

Lists

Introduction

A list is a type of sequence of data points such as float, integer,


or data points

You’re supposed to make a list by encapsulate within [ ].

Python 11
And between this, you’ve to separate the items using ‘ ‘.

For indexing a particular element - “Name of list”[index of


element]

The list indexing begin with 0.

If you’ve extract the element from the end, you can use the
indexing as -1. -2…

Creating a list

participants = ['John', 'Laila', 'Jack', 'Andrew']


print(participants)

['John', 'Laila', 'Jack', 'Andrew']

Extracting from list

Ex. 1

participants = ['John', 'Laila', 'Jack', 'Andrew']


participants[0]

'John'

Ex. 2

participants = ['John', 'Laila', 'Jack', 'Andrew']


participants[-1]

'Andrew'

For deleting value from list

participants = ['John', 'Laila', 'Jack', 'Andrew']


del participants[0]

Python 12
print(participants)

['Laila', 'Jack', 'Andrew']

Updating value in list

participants = ['John', 'Laila', 'Jack', 'Andrew']


participants[0] = 'Erick'
participants

['Erick', 'Laila', 'Jack', 'Andrew']

Built-in method

Syntax
object.method()

1. ‘.’ (period) --> Call or invoke a function

2. method() --> The main method that will work for what's
needed

Methods

list_name.append()

This in-built function allows us to append or add things in


the list.

participants = ['John', 'Laila', 'Jack', 'Andre


participants.append("Aditya")
participants

['John', 'Laila', 'Jack', 'Andrew', 'Aditya']

list_name.extend()

Python 13
This in-built function is used for extending the list or
combining two list into one

participants = ['John', 'Laila', 'Jack', 'Andre


participants.extend(['George', 'Catherine'])
participants

['John', 'Laila', 'Jack', 'Andrew', 'Aditya',

participants = ['John', 'Laila', 'Jack', 'Andre


participants2 = ['George', 'Catherine']
participants.extend(participants2)
participants

['John', 'Laila', 'Jack', 'Andrew', 'Aditya',

list_name.index()

For finding the index of particular element

participants = ['John', 'Laila', 'Jack', 'Andre


participants.index("Laila")

list_name.sort()

Sorts object of list based on alphabetical order and on


numbers.

In forward alphabetical order

participants = ['John', 'Laila', 'Jack', 'An


participants.sort()

Python 14
participants

In reverse alphabetical order

participants = ['John', 'Laila', 'Jack', 'An


participants.sort(reverse = True)
participants

['Laila', 'John', 'Jack', 'George', 'Catheri

In ascending order

numbers = [2, 1, 3, 4, 5]
numbers.sort()
numbers

[1, 2, 3, 4, 5]

In descending order

numbers = [2, 1, 3, 4, 5]
numbers.sort(reverse = True)
numbers

[5, 4, 3, 2, 1]

Calculating length of list

participants = ['John', 'Laila', 'Jack', 'Andrew', 'A


len(participants)

List slicing

Python 15
This is done to extract a particular list from the bigger list. It’s
inclusive of the initial numbers and exclusive of the 2nd number.

participants = ['John', 'Laila', 'Jack', 'Andrew', 'A


participants[1:3]

['Laila', 'Jack']

participants = ['John', 'Laila', 'Jack', 'Andrew', 'A


participants[:2]

['John', 'Laila']

participants = ['John', 'Laila', 'Jack', 'Andrew', 'A


participants[3:]

['Andrew', 'Aditya', 'George', 'Catherine']

For joining different lists

participants = ['John', 'Laila', 'Jack', 'Andrew', 'A


new_participants = ['Keshav', 'Mahima', 'Shreya', 'Si
new_list = [participants, new_participants]
new_list

Python 16
[['John', 'Laila', 'Jack', 'Andrew', 'Aditya', 'Georg
['Keshav', 'Mahima', 'Shreya', 'Siddharth']]

Tuples

Introduction

Tuples are a type of data sequences

They are immutable that means their value can’t be update once
they’re formed

The major difference between lists and tuples in the syntax is


lists use bracket[] and tuple use parentheses()

Functions can provide tuple as return values

Any value that is comma separated becomes tuple by default

Creating a tuple

y = 1, 2, 3
y

(1, 2, 3)

OR

x = (3, 4, 5)
x

(3, 4, 5)

Combining two tuple in list

List1 = [x, y]
List1

[(3, 4, 5), (1, 2, 3)]

Python 17
Extracting from tuple

(age, no_of_years) = "23,10".split(",")


print(age)
print(no_of_years)

23
10

Tuple in function

def area_or_perimeter(x):
area = x**2
perimeter = x*4
print("The area and perimeter is ")
return area, perimeter

area_or_perimeter(5)

The area and perimeter is


(25, 20)

Dictionaries

Introduction

Another way of storing data

It has a key and its value, so it will be key-value pair

You’re supposed to use curly braces {}

Keys can be used to extract the values from the dictionary

Creating a dictionary

dict = {'Name' : 'Aditya', 'Age' : '22', 'Salary' :


dict

Python 18
{'Name': 'Aditya', 'Age': '22', 'Salary': '90,000'}

Extracting value from key

dict['Name']

'Aditya'

Adding value in dictionary

dict['gender'] = 'Male'
dict

{'Name': 'Aditya', 'Age': '22', 'Salary': '90,000',

Combining list into a dictionary

Menu = {'meal_1':'Spaghetti', 'meal_2':'Fries', 'meal


Dessert = ['Pancakes', 'Ice-cream', 'Tiramisu']
Menu['meal_5'] = 'Soup'
Menu['meal_6'] = Dessert
print(Menu)

{'meal_1': 'Spaghetti', 'meal_2': 'Fries', 'meal_3':

.get() method

If the key actually exists

dict = {'Name' : 'Aditya', 'Age' : '22', 'Salary'


dict.get('Name')

'Aditya'

If the key doesn’t exist

Python 19
dict = {'Name' : 'Aditya', 'Age' : '22', 'Salary'
print(dict.get('Gender'))

None

Iterations
Iteration is the ability to execute certain code repeatedly.

for loop

Eg syntax

list = [3,4,7,8,9]
for n in list:
print(n)

3
4
7
8
9

OR

list = [3,4,7,8,9]
for n in list:
print(n, end = " ")

3 4 7 8 9

Reading list using for loop

x = [1,2,3]
for item in x:
print(item, end = " ")

Python 20
1 2 3

OR

x = [1,2,3]
for item in range(len(x)):
print(item+1, end = " ")

1 2 3

x = [1,2,3]
for item in range(len(x)):
print(x[item], end = " ")

1 2 3

while loop

x = 0
while x<=20:
print(x, end = " ")
x=x+2

0 2 4 6 8 10 12 14 16 18 20

range()

Introduction

range(start, stop, step) creates a sequence of integers.

If you don’t provide a start value, then it takes the default value
as 0, and step value as 1 as well.

The start is inclusive but the stop value is exclusive

Python 21
list(range(10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range() in for loop

Finding the different powers of 2 upto 2^10

for i in range(1, 11):


print(2**i, end = " ")

2 4 8 16 32 64 128 256 512 1024

Iterating over list

def count(numbers):
total = 0
for a in numbers:
if a<20:
total+=1
return total
list_1 = [17, 15, 21, 34]
count(list_1)

nums = [1,35,12,24,31,51,70,100]

def count(number):
while len(number)<len(number)+1:
total = 0
for a in number:
if a<20:
total+=1
return total

Python 22
print(count(nums))

Iterating over dictionary

prices = {
"box_of_spaghetti" : 4,
"lasagna" : 5,
"hamburger" : 2
}
quantity = {
"box_of_spaghetti" : 6,
"lasagna" : 10,
"hamburger" : 0
}
money_spent = 0
for i in prices:
money_spent= money_spent + (prices[i]*quantity[i])
print(money_spent)

It basically iterates for key and so based on the indexing of the key, we
got the values

74

OOPS (Object Oriented Programming)

Definition

Object

An object is a fundamental building block that represents a


specific instance of a class. It encapsulates data (attributes or
properties) and behavior (methods or functions) into a single
entity.

Class
Defines the rule of creating an object

Python 23
Eg

1. List is the class

2. Object is the values in it

3. float or integer is the type of variable present in it

4. .extend() and .index() could be the methods

Function vs method

Function Method

Can have many parameters The object is one of its parameters

Exists on its own Belongs to a certain class


function() object.method()

Module, Package and Standard Library

1. Module

Pre-written code containing definitions of variables, functions


and classes

Can be loaded in all new programs

2. Package or library

A collection of related python modules

3. Python standard library

A collection of module as soon as you install python

Importing module eg
Method 1

import math
math.sqrt(4)

2.0

Python 24
Method 2

from math import sqrt


sqrt(16)

4.0

Method 3

from math import sqrt as sq


sq(25)

5.0

Method 4

import math as m
m.sqrt(36)

6.0

💡 help(math) will provide all the functionalities of math module

help(math.sqrt) will provided the functionality of square root

Software documentation

1. A collection of information stored as written text, illustrations or


both which accompanies the features of the software tool and

Python 25
assists its users.

2. Click shift+tab in jupyter to know the documentation of the


particular thing

Matrices and array

1. The simplest way to work with matrices in python is using arrays.

Scalar

All numbers we know from algebra are referred to as scalars in


linear algebra

[15], [1], [2]

Scalars have no dimension, just the single value

Length - The no of elements in a vector

It’s just single element (1*1)

import numpy as np
v = np.array(5)
v

array(5)

Vectors
It’s 1*m or m*1

import numpy as np
v = np.array([2,3,-4])
v

array([ 2, 3, -4])

Matrices

1. It’s m*n

2. A matrix is a collection of numbers ordered in rows and columns

Python 26
3. It’s collection of vectors or scalars

import numpy as np
m = np.array([[2,3,4], [5,-2,-6]])
m

array([[ 2, 3, 4],
[ 5, -2, -6]])

Finding type of the array

type(m)

numpy.ndarray

1D Array (Vector) vs 2D Array (Matrix)


The shape() function tells the shape of the array

1D Array

v = np.array([2, 3, 4])
print(v.shape) # Output: (3,)

2D Array

v = np.array([[2, 3, 4]])
print(v.shape) # Output: (1, 3)

This is a 2D array (matrix) with 1 row and 3 columns.

The first element of the shape (1, 3) represents the number of


rows (1 row).

v = np.array([[2], [3], [4]])

Python 27
print(v.shape) # Output: (3, 1)

This is a 2D array with 3 rows and 1 column.

The first element of the shape (3, 1) represents the number of


rows (3 rows).

💡 The other variables such as int, float won’t have any shape
and they will throw an error but if you make them using array,
python won’t show any error

object.reshape() method

Gives an array a new shape, without changing its data

import numpy as np
v = np.array([1,2,3])
print(v.shape)
print(v.reshape(3,1))
print(v.reshape(1,3))

(3,)
[[1]
[2]
[3]]
[[1 2 3]]

Tensors
This is an overall generalization or scalar, vector and matrices

Creating tensor using two matrices

import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
t = np.array([v,m])

Python 28
print(t)
print(t.shape)

array([[[ 3, 2, 4],
[ 4, -2, 1]],

[[ 2, 6, 7],
[ 1, -7, 2]]])

(2, 2, 3) #shape of the tensor

Creating tensor manually

t_manual = np.array([[[3,2,4],[4,-2,1]], [[2,6,7],[1


t_manual

array([[[ 3, 2, 4],
[ 4, -2, 1]],

[[ 2, 6, 7],
[ 1, -7, 2]]])

Python 29
Addition and subtraction

Addition

import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
v+m

array([[ 5, 8, 11],
[ 5, -9, 3]])

Subtraction

import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
v-m

array([[ 1, -4, -3],


[ 3, 5, -1]])

Adding with scalar

1. Normally, if you try to add or subtract matrices of different


length, it will show an error.

2. The matrices or vector, should always be of the same dimension

3. But the only exception is the addition of scalar and matrices

import numpy as np
v = np.array([[3,2,4],[4,-2,1])
v+1

array([[ 4, 3, 5],
[ 5, -1, 2]])

Python 30
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([1])
v+m

array([[ 4, 3, 5],
[ 5, -1, 2]])

Transposing vectors

Introduction

The values doesn’t change, only the position changes

Transposing the same vector twice leads to the same position


as before

A 3*1 matrix would be 1*3 matrix

It doesn’t work as such on scalars or 1D arrays. Only if you


reshape into 2D array, then transpose is gonna work. It can be
verified by checking the shape using shape() function.

Python 31
Syntax

import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
v.T #.T is what needed for transposing

array([[ 3, 4],
[ 2, -2],
[ 4, 1]])

Dot product or scalar product

Introduction

It’s called as scalar product because it returns a scalar quantity

The final value after addition will be [-66] which is a scalar

Syntax

import numpy as np
v = np.array([2,8,-4])
m = np.array([1,-7,3])
np.dot(v,m)

np.int64(-66)

Scalar*Scalar

import numpy as np
np.dot(5,6)

Python 32
np.int64(30)

Scalar*vector

import numpy as np
x = np.array([5,2,3])
print(x)
print(x*5)

[5 2 3]
[25 10 15]

Dot product of matrices

Introduction

The important rule is to the remember that the second


dimension of the first matrices must be same as first dimension
of the second matric

Ex. m*n and n*k can undergo dot product and would result in
m*k matrix

Python 33
Syntax

import numpy as np
x = np.array([[5,2,3],[1,2,3]])
y = np.array([[3,2],[4,3],[5,7]])
np.dot(x,y)

array([[38, 37],
[26, 29]])

NumPy (Numeric+Python)

Python 34
Introduction

1. A collection of pre-written functions, classes and methods which


are capable of handling and manipulating data and calculating
results

2. Main feature: To manipulate arrays

3. Why use NumPy: Computationally very stable and efficient

4. It works in lower level language which leads to shorter computation


time

5. When do we use it? —>

a. Compute a lot of value for analysis

b. Deals with vectors and scalars

c. Import and pre-process data into python directly

d. Fantastic tool for generating tests

6. Arrays look similar to python’s list but array is more useful when
computing values because they work element wise (array)

7. NumPy functions and methods are faster than python methods and
functions

Syntax

Importing, installing, upgrading and checking the version of NumPy

import numpy as np
np.__version__

pip install numpy --upgrade

Creating array variable

import numpy as np
array_hw_1 = np.array([4,5,7,10])
print(array_hw_1)

Python 35
[ 4 5 7 10]

Creating 2*2 array

import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
array_hw_1

array([[ 4, 5, 7, 10],
[ 2, 3, 6, 7]])

Mean of array

Syntax

numpy.mean(a, axis=None, dtype=None, out=None, kee

Normal mean

import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1)

np.float64(5.5)

Mean across all columns

import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 0)

array([3. , 4. , 6.5, 8.5])

Mean across all rows

Python 36
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1)

array([6.5, 4.5])

For specifying the data type


We can specify the datatype using dtype

For specifying integer

import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1, dtype = int)

array([6, 4])

For specifying float

import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1, dtype = float)

array([6.5, 4.5])

Pandas (Panel+Data)

Introduction

1. Panel+Data - Data sets that include multiple observations over


multiple periods of time.

2. Multiple observations over multiple period of time

3. Used for text, Boolean and date time

Python 37
4. pandas need the computational power and abilities of NumPy to
perform its computations so that you can focus on the analytical
task and less on the underlying mathematical computations

5. Two data structures are at the core They store the data and allow us
to the manipulations on it. They are -

a. Series (single-column data) - A set of observations related to


single variable. It corresponds to 1D array in NumPy.

b. Data-frames (multiple-column data) - A collection of series


objects, which contains observations related to one or several
variables. It corresponds to 2D arrays in NumPy

6. It’s an open source, BSD-licensed library providing high-


performance, easy-to-use data structures and data analysis tools
for the python.

7. It’s not one of the essential components of scientific computing


tools like numpy or matplotlib.

8. It’s best for analyzing dataset that contains multiple types of


information

Attributes vs methods

Aspect Attribute Method

Nature Stores data/state. Executes code/logic.

Accessed directly as a Requires parentheses () to


Access
variable. call.

Holds information about the Performs an action or


Purpose
object. operation.

Example
object.attribute object.method()
Syntax

Can modify attributes or


Change
Cannot modify itself. perform
State
computations.

Pandas Series Object

1. It’s a powerful version of python list or an enhanced version of


NumPy array

Converting list to pandas series

Python 38
import pandas as pd
product = ['A','B','C','D']
product_category = pd.Series(product)
product_category

0 A
1 B
2 C
3 D
dtype: object

Checking the datatype

import pandas as pd
product = ['A','B','C','D']
product_category = pd.Series(product)
type(product_category)

pandas.core.series.Series

Converting NumPy array to pandas series

import numpy as np
array_1 = np.array([1,2,3,4,5])
array_2 = pd.Series(array_1)
array_2

0 1
1 2
2 3
3 4
4 5
dtype: int64

Working with attributes and methods

Python 39
Introduction

1. Python object contains

a. Data

b. Metadata

c. related functionalities

2. Attribute - The variable providing meta data of an object

3. Method - A function that can be associated with an object

4. Almost every entity in python is an object

object_name.dtype

import pandas as pd
product_category = pd.Series([1,2,3,4,5])
product_category.dtype

dtype('int64')

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.dtype

dtype('O')

object_name.size

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.size

Python 40
One of the most interesting thing about attribute is that it can be
used for further calculation.

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
type(product_category.size)

int

object_name.name

In Pandas, the .name attribute is commonly used for Series


objects and DataFrame index levels to provide or retrieve a
label for the data.

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.name = "Product Category"
product_category

0 A
1 B
2 C
3 D
Name: Product Category, dtype: object

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.name = "Product Category"
print(product_category.name)

Product Category

object_name.to_numpy()

Python 41
The method to_numpy() in Pandas converts the data in a Pandas
object (like a Series or DataFrame) into a NumPy array.

import pandas as pd
product_category = pd.Series(['A','B','C','D'])
x = product_category.to_numpy()
print(type(x))

Indexing in pandas

Introduction

1. An index allows you to refer to a position within a sequence

2. The index data structures helps in speeding up the


computation while working with large datasets

prices_per_category = {'Product A':'22500',


'Product B':'23000','Product C':'25240'}
prices_per_category = pd.Series(prices_per_cate
prices_per_category

Product A 22500
Product B 23000
Product C 25240
dtype: object

index

prices_per_category = {'Product A':'22500', 'Prod


prices_per_category = pd.Series(prices_per_catego
prices_per_category.index

Index(['Product A', 'Product B', 'Product C'], dty

type of index

Python 42
prices_per_category = {'Product A':'22500',
'Product B':'23000','Product C':'25240'}
prices_per_category = pd.Series(prices_per_catego
type(prices_per_category.index)

pandas.core.indexes.base.Index

Python 43

You might also like