0% found this document useful (0 votes)
4 views122 pages

Python Dataanalysis 1

This document provides an overview of Python programming concepts including data analysis, variables, data types, operators, functions, and control flow statements. It includes code examples demonstrating the use of comments, arithmetic operations, and built-in functions. The content is structured over multiple days, focusing on foundational Python skills for data analysis.

Uploaded by

fekexic361
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)
4 views122 pages

Python Dataanalysis 1

This document provides an overview of Python programming concepts including data analysis, variables, data types, operators, functions, and control flow statements. It includes code examples demonstrating the use of comments, arithmetic operations, and built-in functions. The content is structured over multiple days, focusing on foundational Python skills for data analysis.

Uploaded by

fekexic361
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

python-dataanalysis-1

August 9, 2024

1 day1-Python for data analysis


lets start
[3]: a='hellowolrd'
print(a)

hellowolrd

[4]: print(2+3+5*4)

25

2 PYTHON COMMENTS
[5]: #this is comment
print('Hello World')

Hello World

[7]: '''this is our first class'''


print(3)

3 day 2 variables and operators


[8]: #variables store values
x=5
y='Rizwan Shaikh'
print(x)
print(y)

5
Rizwan Shaikh

[9]: x,y,z='apple','orange','banana'
print(x,y,z)

1
apple orange banana
Many values to multiple variable
[10]: x=y=z="orange"
print(x,y,z)

orange orange orange


python output variables
[13]: x='python'
y=' is'
z=' amazing'
print(x + y + z)

python is amazing

4 Data Types
[15]: x=2
print(x)
print(type(x))

2
<class 'int'>

[16]: y=4.5
print(y,type(y))

4.5 <class 'float'>

[17]: z=2+5j
print(z)
print(type(z))

(2+5j)
<class 'complex'>

[19]: a='The day was really amazing'


print(a)
print(type(a))

The day was really amazing


<class 'str'>

[20]: a=[1,2,3,4,5,6,7,8,9]
print(a)
print(type(a))

2
[1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'>

[21]: a=(1,2,3,4,5,6,7,8,9)
print(a)
print(type(a))

(1, 2, 3, 4, 5, 6, 7, 8, 9)
<class 'tuple'>

[23]: %whos #shows all the variables created

Variable Type Data/Info


-------------------------------
a tuple n=9
pandas module <module 'pandas' from 'C:<…>es\\pandas\\__init__.py'>
x int 2
y float 4.5
z complex (2+5j)

5 Operators
[ ]: #Addition operator
a=5
b=95
print(a+b)

[25]: a=5.3
b=6.6
print(a+b)

11.899999999999999

[26]: a=5+2j
b=7
print(a+b)

(12+2j)

[27]: a='student'
b='hello'
print(a+" "+b)

student hello
subtraction

3
[28]: a=15
b=5
print(a-b)

10

[29]: a=5+6j
b=9
print(a-b)

(-4+6j)
multiplication
[30]: a=15
b=5
print(a*b)

75

[31]: a=5.56
b=1
print(a*b)

5.56
division
[32]: a=10
b=5
print(a/b)

2.0
Modulus
[33]: a=19
b=3
print(a%b)

[34]: a=12
b=3
print(a%b)

0
exponent

4
[35]: a=4
print(a**2)

16

[36]: a=102
print(a**15)

1345868338324129592144306208768

[38]: a=((80*2)+3+90-100)**2
print(a)

23409

[39]: a=True
b=False
print(a and b)

False

[40]: print(a or b)

True

[41]: a = True
b= False
print(not(a))

False

[42]: print(not(b))

True

[44]: a=((8922*2852)+(7821*222)-(25566*256)+(8281/82))
print(a)

20637010.98780488

6 Day 3 Python Function


1)Builtin Function , 2)Python Recursive Function , 3)Python Lambda Function , 4)User-Defined
Function in Python.

7 Built in Functions
abs() Function

5
[45]: #abs is absolute function converts negative values to positive
x=abs(-7.25)
print(x)

7.25

[46]: y=abs(-8)
print(y)

[47]: z=abs(3+5j)
print(z)

5.830951894845301
Binary Function
[48]: #bin is binary function
x= bin(13)
print(x)

0b1101

[49]: y = bin(36)
print(y)

0b100100

[50]: z=bin(64)
print(z)

0b1000000
Bytes Function , bytes Function
[51]: x=bytes(4)
print(x)

b'\x00\x00\x00\x00'

[52]: y=bytes(100)
print(y)

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00'

6
Character Function , chr fun
[54]: #chr() function
x=chr(97)
print(x)

[55]: y = chr(98)
print(y)

[56]: z = chr(99)
print(z)

[57]: v = chr(94)
print(v)

^
Complex Function
[58]: x = complex(3,5)
print(x)

(3+5j)

[59]: y = complex(10,15)
print(y)

(10+15j)

[60]: z=complex(2.5,3.96)
print(z)

(2.5+3.96j)

[61]: v = complex('2')
print(v)

(2+0j)

7
8 Floating Function ,float() function
[62]: x = (float(3))
print(x)

3.0

[63]: y =float(3.56)
print(y)

3.56

[65]: z=float(5)
print(z)

5.0
int Function
[66]: x=int(3.9)
print(x)

[67]: y=int(9.0)
print(y)

[70]: z=int(3+5j)
print(z)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[70], line 1
----> 1 z=int(3+5j)
2 print(z)

TypeError: int() argument must be a string, a bytes-like object or a real␣


↪number, not 'complex'

string Function, str() function

[71]: a= str('2568')
print(a)
print(type(a))

2568
<class 'str'>

8
[72]: a=str('14.88')
print(a)
print(type(a))

14.88
<class 'str'>
help()n function

[73]: help(print)

Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)


Prints the values to a stream, or to [Link] by default.

sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current [Link].
flush
whether to forcibly flush the stream.

[74]: help(float)

Help on class float in module builtins:

class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.

9
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|

10
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)

11
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
| Return a pair of integers, whose ratio is exactly equal to the original
float
| and with a positive denominator.
|
| Raise OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> [Link]()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /) from [Link]
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or
'IEEE,

12
| little-endian' best describes the format of floating point numbers used
by the
| C type named by typestr.
|
| fromhex(string, /) from [Link]
| Create a floating-point number from a hexadecimal string.
|
| >>> [Link]('0x1.ffffp10')
| 2047.984375
| >>> [Link]('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from [Link]
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number

input() function

[76]: x=input('Enter your name: ')


print(x)

Enter your name: rizwan


rizwan

[84]: y = input('enter your age')


if y <= '25':
print('You Are Selected')
else:
print('you are rejected')

enter your age25


You Are Selected

[86]: a=input('Enter your name : ')


b=input('Enter your Age : ')
print(a,b)

13
Enter your name : Rizwan
Enter your Age : 21
Rizwan 21

9 Day4 Control Flow Statement in Python


if conditions
[91]: ''' Make a Student Result Using Python '''
#calculate the percentage of a student in the subjects maths science social␣
↪english and hindi

x=input('Enter the name of the student: ')


a=int(input('Enter the marks in maths: '))
b=int(input('Enter the marks in science: '))
c=int(input('Enter the marks in social: '))
d=int(input('Enter the marks in english: '))
e=int(input('Enter the marks in hindi: '))
n=((a+b+c+d+e)/500)*100
print('Percentage of the student is ',n)

Enter the name of the student: Rizwan Shaikh


Enter the marks in maths: 98
Enter the marks in science: 96
Enter the marks in social: 92
Enter the marks in english: 85
Enter the marks in hindi: 85
Percentage of the student is 91.2

[93]: a=int(input('Enter the percentage scored: '))


if a>=90:
print('Grade A')
if a>=75 and a<90:
print('Grade B')
if a<75 and a>50:
print('Grade C')

Enter the percentage scored: 95


Grade A
if else statement
[97]: x=input('Enter the candidate Name: ')
a=int(input('Enter the candidate Age: '))
if a>=18:
print('You are eligible to vote for the election as your age is',a)
else:
print('You are not eligible to vote for the election as your age is',a)

Enter the candidate Name: Rizwan Shaikh

14
Enter the candidate Age: 21
You are eligible to vote for the election as your age is 21

[106]: # Write a program to display if the number entered by a user is a multiple of 5␣


↪else print bye

x=int(input('Enter the Number:'))


if x%5==0:
print('Hello')
else:
print('Bye')

Enter the Number:30


Hello

[109]: a = int(input('Enter the number:'))


if a>0:
print('The number is positive:',a)
else:
print('The number is negative:',a)

Enter the number:-25


The number is negative: -25
if elif else statement
#Accept the city and print its monument
Delhi-Red fort, Agra - Taj mahal, Jaipur - Jalmahal, Pune - Shaniwar wada, other- Record not
Found.
[133]: city=input(' Enter the name of the City: ')
if city == 'Delhi':
print('The Monument in Delhi is Red Fort')
elif city == 'Agra':
print('The Monument in Agra is Taj Mahal')
elif city =='Jaipur':
print('The Monument in Jaipur is Jal Mahal')
elif city=='Pune':
print('The Monument in Pune is Shaniwar Wada')
else:
print('Record Not Found')

Enter the name of the City: Delhi


The Monument in Delhi is Red Fort

10 Day-5 Loops
While Loop

15
[127]: #program to display numbers from 1 to 5
i = 1
n = 5
while i<=n:
print(i)
i = i+1
print('the program ends')

1
2
3
4
5
the program ends

[129]: #program to make a multiplication table till 10


x=int(input('Enter the number:'))
i=1
while i<=10:
print(x*i)
i=i+1
print('this is the multiplication table of',x)

Enter the number:10


10
20
30
40
50
60
70
80
90
100
this is the multiplication table of 10
infinite while loop
[200]: count=0
while (count<5):
count = count +1
print('Hello student')

Hello student
Hello student
Hello student
Hello student
Hello student

16
Using else Statement in the while loop
[201]: count=0
while (count<5):
count = count +1
print('Hello student')
else:
print('this is the else block')

Hello student
Hello student
Hello student
Hello student
Hello student
this is the else block
For Loop (for list,tuple and string)

[137]: fruits = ["apple","banana","mango","cherry"]


for x in fruits:
print(x)

apple
banana
mango
cherry
looping through a string
[138]: for x in "banana":
print(x)

b
a
n
a
n
a

[139]: for x in range(1,26):


print(x)

1
2
3
4
5
6
7
8

17
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

[140]: for x in range(1,20,2):


print(x)

1
3
5
7
9
11
13
15
17
19

11 Day-6 User Defined Functions (def Keyword )


[141]: def my_function():
print('hello class')

my_function()

hello class

[157]: #Creat A students Result using the input data


def contact():
print('Contact details of the school')
print('Delhi public school')
print('Banglore karnataka')

18
print('997091550')
print('rizu2705@[Link]')

[162]: for i in range(1,3):


a=input('enter the name of the student:')
b=int(input('enter the marks of maths:'))
c=int(input('enter the marks of science:'))
d=int(input('enter the marks of social science:'))
e=int(input('enter the marks of english:'))
n=((b+c+d+e)/400)*100
print(),print('the percentage obtain is:',n)
contact()

enter the name of the student:Rizwan Shaikh


enter the marks of maths:96
enter the marks of science:98
enter the marks of social science:85
enter the marks of english:92

the percentage obtain is: 92.75


Contact details of the school
Delhi public school
Banglore karnataka
997091550
rizu2705@[Link]
enter the name of the student:Rehan Shaikh
enter the marks of maths:80
enter the marks of science:95
enter the marks of social science:75
enter the marks of english:75

the percentage obtain is: 81.25


Contact details of the school
Delhi public school
Banglore karnataka
997091550
rizu2705@[Link]
Arguments
[165]: def my_function(fname):
print(fname + " sharma")

my_function("Pooja")

Pooja sharma

19
[166]: def name(fname,lastname):
print(fname + ' '+lastname)

[167]: name('rizwan','shaikh')

rizwan shaikh

[ ]: #write a program to calculate a electricity bill


if 500 units used - pay Rs 5 for each unit
if 700 units used - pay Rs 10 for each unit
if 1000 units used - pay Rs 15 for each unit
if more than 1000 unit used - pay Rs 20 for each unit

[190]: def electricity_bill(consumer_name,n):


print(consumer_name)
print('Your Bill of the Month is')
print('Your units used for electricity bill is unit',n)
if n<=500:
print('Your bill is Rs ', n*5)
elif n>500 and n<=700:
print('Your bill is Rs ',n*10)
elif n>700 and n<=1000:
print('Your bill is Rs ',n*15)
elif n>1000:
print('Your bill is Rs',n*20)

[191]: electricity_bill('Rizwan shaikh',550)

Rizwan shaikh
Your Bill of the Month is
Your units used for electricity bill is unit 550
Your bill is Rs 5500

[192]: electricity_bill('Rehan Shaikh',400)

Rehan Shaikh
Your Bill of the Month is
Your units used for electricity bill is unit 400
Your bill is Rs 2000

[194]: def electricity_bill(n):


if n<=500:
print('Your bill is Rs ', n*5)
elif n>500 and n<=700:
print('Your bill is Rs ',n*10)
elif n>700 and n<=1000:
print('Your bill is Rs ',n*15)

20
elif n>1000:
print('Your bill is Rs',n*20)

[195]: def instruction():


print('Last day of paying your bill is 30 april')
print('After 20 april you need to pay 1000 Rs as a Fine')
print('Electricity Office Pune')

[198]: for i in range(3):


a=input('ENTER THE NAME OF CONSUMER:')
n=int(input("Enter the units of Electricity you have used "))
electricity_bill(n)
print()
instruction()

ENTER THE NAME OF CONSUMER:Rizwan Shaikh


Enter the units of Electricity you have used 550
Your bill is Rs 5500

Last day of paying your bill is 30 april


After 20 april you need to pay 1000 Rs as a Fine
Electricity Office Pune
ENTER THE NAME OF CONSUMER:Rehan Shaikh
Enter the units of Electricity you have used 1100
Your bill is Rs 22000

Last day of paying your bill is 30 april


After 20 april you need to pay 1000 Rs as a Fine
Electricity Office Pune
ENTER THE NAME OF CONSUMER:Zaffar Shaikh
Enter the units of Electricity you have used 450
Your bill is Rs 2250

Last day of paying your bill is 30 april


After 20 april you need to pay 1000 Rs as a Fine
Electricity Office Pune

12 Day-7 Strings
Immuteable data type- which cannot be changed string=”,” “,””” ”””
[1]: a='Hello Rizwan'
print(a)

Hello Rizwan

21
[2]: b='We are learning python for data analysis'
print(b)
print(type(b))

We are learning python for data analysis


<class 'str'>
Multiline Strings
[5]: b='India,officially the Republic of India (ISO: Bhārat Gaṇarājya),[21] is a␣
↪country in South Asia. It is the seventh-largest country by area; the most␣

↪populous country as of June 2023;[22][23] and from the time of its␣

↪independence in 1947, the worlds most populous democracy.[24][25][26]␣

↪Bounded by the Indian Ocean on the south, the Arabian Sea on the southwest,␣

↪and the Bay of Bengal on the southeast, it shares land borders with Pakistan␣

↪to the west;[j] China, Nepal, and Bhutan to the north; and Bangladesh and␣

↪Myanmar to the east. In the Indian Ocean, India is in the vicinity of Sri␣

↪Lanka and the Maldives; its Andaman and Nicobar Islands share a maritime␣

↪border with Thailand, Myanmar, and Indonesia.'

print(b)

India,officially the Republic of India (ISO: Bhārat Gaṇarājya),[21] is a country


in South Asia. It is the seventh-largest country by area; the most populous
country as of June 2023;[22][23] and from the time of its independence in 1947,
the worlds most populous democracy.[24][25][26] Bounded by the Indian Ocean on
the south, the Arabian Sea on the southwest, and the Bay of Bengal on the
southeast, it shares land borders with Pakistan to the west;[j] China, Nepal,
and Bhutan to the north; and Bangladesh and Myanmar to the east. In the Indian
Ocean, India is in the vicinity of Sri Lanka and the Maldives; its Andaman and
Nicobar Islands share a maritime border with Thailand, Myanmar, and Indonesia.

[7]: c="""India,officially the Republic of India (ISO: Bhārat Gaṇarājya),[21] is a␣


↪country in South Asia.

It is the seventh-largest country by area; the most populous country as of June␣


↪2023;[22][23] and from the time of its independence in 1947, the worlds most␣

↪populous democracy.[24][25][26]

Bounded by the Indian Ocean on the south, the Arabian Sea on the southwest, and␣
↪the Bay of Bengal on the southeast, it shares land borders with Pakistan to␣

↪the west;[j] China, Nepal, and Bhutan to the north; and Bangladesh and␣

↪Myanmar to the east.

In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives;␣
↪its Andaman and Nicobar Islands share a maritime border with Thailand,␣

↪Myanmar, and Indonesia."""

print(c)

India,officially the Republic of India (ISO: Bhārat Gaṇarājya),[21] is a country


in South Asia.
It is the seventh-largest country by area; the most populous country as of June

22
2023;[22][23] and from the time of its independence in 1947, the worlds most
populous democracy.[24][25][26]
Bounded by the Indian Ocean on the south, the Arabian Sea on the southwest, and
the Bay of Bengal on the southeast, it shares land borders with Pakistan to the
west;[j] China, Nepal, and Bhutan to the north; and Bangladesh and Myanmar to
the east.
In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives; its
Andaman and Nicobar Islands share a maritime border with Thailand, Myanmar, and
Indonesia.
Indexing of string
[11]: a='Hello Student'
print(a[11])

[12]: a[0:14:2]

[12]: 'HloSuet'

[14]: a[-1]

[14]: 't'

[17]: a[-1:-5]

[17]: ''

[18]: a[-7]

[18]: 'S'

[22]: a=" How's your studying going on "


a[1:]
print(len(a))

30

[24]: a='Hello students Rizwan here'


for index,char in enumerate(a):
print(index,char)

0 H
1 e
2 l
3 l
4 o
5

23
6 s
7 t
8 u
9 d
10 e
11 n
12 t
13 s
14
15 R
16 i
17 z
18 w
19 a
20 n
21
22 h
23 e
24 r
25 e
Slicing of Strings
[26]: a='Hello Students How Are You All' #[start,stop,step]
a[6:18]

[26]: 'Students How'

[29]: a[0:5]

[29]: 'Hello'

[30]: a[0:]

[30]: 'Hello Students How Are You All'

[33]: a[-5]

[33]: 'u'

[36]: a[0:20:2]

[36]: 'HloSuet o '

[37]: a[::-1]

[37]: 'llA uoY erA woH stnedutS olleH'

Fininding the length of the string

24
[38]: x="""India,officially the Republic of India (ISO: Bhārat Gaṇarājya),[21] is a␣
↪country in South Asia.

It is the seventh-largest country by area; the most populous country as of June␣


↪2023;[22][23] and from the time of its independence in 1947, the worlds most␣

↪populous democracy.[24][25][26]

Bounded by the Indian Ocean on the south, the Arabian Sea on the southwest, and␣
↪the Bay of Bengal on the southeast, it shares land borders with Pakistan to␣

↪the west;[j] China, Nepal, and Bhutan to the north; and Bangladesh and␣

↪Myanmar to the east.

In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives;␣
↪its Andaman and Nicobar Islands share a maritime border with Thailand,␣

↪Myanmar, and Indonesia."""

print(len(c))

706

[39]: b='Hello World' #Spaces are also calculated in the example


print(len(b),b)

11 Hello World
upper method
[41]: a = 'hello how are you! hope so fine and good'
[Link]()
print([Link]())

HELLO HOW ARE YOU! HOPE SO FINE AND GOOD


Lower method
[42]: b='HELLO HOW ARE YOU! HOPE SO FINE AND GOOD'
print([Link]())

hello how are you! hope so fine and good


replace method
[43]: a = 'Rizwan Saikh'
print(a)

Rizwan Saikh

[45]: print([Link]('Saikh','Shaikh'))

Rizwan Shaikh

[47]: a='tow are you!'


print([Link]('t','H'))

25
How are you!
Find Method
[48]: a='python is great'
b=[Link]('g')
print(b)

10

[49]: a[10]

[49]: 'g'

[52]: c=[Link]('p')
print(c)

[53]: d=[Link]('y')
print(d)

[54]: x='All The Ants Are Ants'


y=[Link]('A')
print(y)

[60]: x='All The Ants Are Ants'


index=0
while index < len(x):
if x[index]=='A':
print(f"Index:{index}")
index=index+1

Index:0
Index:8
Index:13
Index:17

13 Day-8 Lists (Mutable-can be changed)


[62]: #List are ordered , changeable , and allow duplicates values
# To create a list the brakets used are []
mylist=['Apple','Banana','kiwi']
print(mylist)

26
print(type(mylist))

['Apple', 'Banana', 'kiwi']


<class 'list'>
Allow Duplicates
[63]: mylist1=['apple','banana','apple','apple']
print(mylist1)

['apple', 'banana', 'apple', 'apple']

[66]: list3=[1,2,3,0.1,0.2,0.5,'Apple',True,False]
print(list3)

[1, 2, 3, 0.1, 0.2, 0.5, 'Apple', True, False]


list length
[67]: list3=[1,2,3,0.1,0.2,0.5,'Apple',True,False]
print(len(list3))

[68]: b = [15,8,7,9,0,1,3,4]
print(len(b))

8
Access Items
[69]: thislist=[12,15,26,78,14,25,142,52,22,6,5]
print(thislist[1])

15

[73]: thislist[10]

[73]: 5

[74]: thislist[-1]

[74]: 5

Slicing of list
[75]: thislist[1::]

[75]: [15, 26, 78, 14, 25, 142, 52, 22, 6, 5]

27
[76]: thislist[0::2]

[76]: [12, 26, 14, 142, 22, 5]

[77]: thislist[::-1]

[77]: [5, 6, 22, 52, 142, 25, 14, 78, 26, 15, 12]

[78]: thislist[4:8]

[78]: [14, 25, 142, 52]

[81]: a=['Apple','Banana','How are you',1,2,3,4]


print(a)
print(type(a))

['Apple', 'Banana', 'How are you', 1, 2, 3, 4]


<class 'list'>

[82]: a[1]

[82]: 'Banana'

[83]: a[::-1]

[83]: [4, 3, 2, 1, 'How are you', 'Banana', 'Apple']

[84]: a[0::2]

[84]: ['Apple', 'How are you', 2, 4]

[85]: a[3]

[85]: 1

[86]: a[2]

[86]: 'How are you'

Changes items in list


[87]: l=['Apple','Banana','Cherry']
print(l)

['Apple', 'Banana', 'Cherry']

[90]: l[1]='Strawberry'
print(l)

28
['Apple', 'Strawberry', 'Cherry']

[91]: a=[12,14,15,16,8,9,-5,-3,41,-9]
a[2]='Student'
print(a)

[12, 14, 'Student', 16, 8, 9, -5, -3, 41, -9]


change a range of items values
[92]: a=[12,14,15,16,8,9,-5,-3,41,-9]
a[2:4]=['books','pen','paper']
print(a)

[12, 14, 'books', 'pen', 'paper', 8, 9, -5, -3, 41, -9]

[94]: a[6:8]=['Rizwan','Shaikh']
print(a)

[12, 14, 'books', 'pen', 'paper', 8, 'Rizwan', 'Shaikh', -3, 41, -9]

[95]: a=[12,14,15,78,90]
[Link](-9)
print(a)

[12, 14, 15, 78, 90, -9]

[96]: [Link](15)
print(a)

[12, 14, 78, 90, -9]

[97]: x=['Rizwan',1,2,3,4]
[Link]('Rizwan')
print(x)

[1, 2, 3, 4]
Reverse of list
[98]: mylist=[1,2,3,4,5,'Python','Data']
[Link]()
print(mylist)

['Data', 'Python', 5, 4, 3, 2, 1]

[100]: l=[14,15,12,78,-9,23,-8,52,74,89,25,102,8]
print(len(l))
a = 0
for i in range(13):

29
a= a + l[i]
i=i+1
print('the sum of a list is',a)

13
the sum of a list is 475

[119]: #multiply all the number of list


x=[1,2,3,4,5,6,7,8,9,10]
print(len(x))
r=1
for a in x:
r=r*a
print('the multiplication is',r)

10
the multiplication is 3628800

[120]: z=[1,2,3,4]
mul=1
for x in z:
mul=mul*x
print('the multiplication of list numbers is',mul)

the multiplication of list numbers is 24

14 Day - 09 TUPLES(Immutable cant be changed once created)


[3]: #tuples =()
#creating a tuple
my_tuple=(1,2,3,4)
print(my_tuple)
print(type(my_tuple))

(1, 2, 3, 4)
<class 'tuple'>

[4]: #mixed Datatype


m1=(1,2,3,4,0.5,0.1010,'hello')
print(m1,type(m1))

(1, 2, 3, 4, 0.5, 0.101, 'hello') <class 'tuple'>

[5]: #tuple
my_tuple=()
print(my_tuple)

30
()

[6]: #nested tuple


a=('data',[1,2,3,4],(5,6,7))
print(type(a),a)

<class 'tuple'> ('data', [1, 2, 3, 4], (5, 6, 7))

[7]: #creating a tupke with only one element


var1=('hello')
print(var1)
print(type(var1))

hello
<class 'str'>

[8]: var2=('hello',)
print(var2,type(var2))

('hello',) <class 'tuple'>

[9]: var3=(5,)
print(var3,type(var3))

(5,) <class 'tuple'>

[12]: #tuple constructor


a=tuple(('a','b','c'))
print(a,type(a))

('a', 'b', 'c') <class 'tuple'>

[14]: #indexing
a=(47,50,60,48,0,5)
a[5]

[14]: 5

[15]: b=(1,2,3,4,5,6,7,8,9,0)
b[-1]

[15]: 0

[16]: b[-6]

[16]: 5

[17]: b[6]

31
[17]: 7

[18]: c=(1,2,3,4,'hello','hi')
c[-1]

[18]: 'hi'

[19]: c[-2]

[19]: 'hello'

[20]: c[4]

[20]: 'hello'

[22]: #slicing
a1=(14,15,17,821,5,852,8,29,2,8,2,4)
len(a1)

[22]: 12

[23]: print(a[0:6])

(14, 15, 17, 821, 5, 852)

[25]: a[::]

[25]: (14, 15, 17, 821, 5, 852, 8, 29, 2, 8, 2, 4)

[26]: a[::4]

[26]: (14, 5, 2)

[27]: a[0:]

[27]: (14, 15, 17, 821, 5, 852, 8, 29, 2, 8, 2, 4)

[28]: a[::10]

[28]: (14, 2)

[29]: a[0:6:2]

[29]: (14, 17, 5)

[30]: #for reversing a tuple


a1=(14,15,17,821,5,852,8,29,2,8,2,4)

32
print(a[::-1])

(4, 2, 8, 2, 29, 8, 852, 5, 821, 17, 15, 14)

[33]: T=(1,2,3,4,5,6,7,8)
print(T[::])
print(T[3::])
print(T[:4])
print(T[-2:-5:-1])

(1, 2, 3, 4, 5, 6, 7, 8)
(4, 5, 6, 7, 8)
(1, 2, 3, 4)
(7, 6, 5)

[34]: T[-2::-1]

[34]: (7, 6, 5, 4, 3, 2, 1)

[39]: t=(1,2,3,3,3,3,3,3)
t

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

[41]: a=(25,26,27,28,29)
y=list(a)
[Link](30)
a=tuple(y)
a

[41]: (25, 26, 27, 28, 29, 30)

[46]: a=(25,26,27,28,29)
y=list(a)
[Link](26)
a=tuple(y)
a

[46]: (25, 27, 28, 29)

[49]: a=(1,2,3,4,5,6,7,8,9)
del a

[50]: print(a)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)

33
Cell In[50], line 1
----> 1 print(a)

NameError: name 'a' is not defined

15 LOOP
[51]: thistuple=('a','b','c')
for x in thistuple:
print(x)

a
b
c

[52]: #join two tuple


tuple1=('a','b','c') #addition
tuple2=(1,2,3)
tuple3=tuple1+tuple2
tuple3

[52]: ('a', 'b', 'c', 1, 2, 3)

[53]: #multipliction
a=('apple','data','python')
b=a*3
b

[53]: ('apple',
'data',
'python',
'apple',
'data',
'python',
'apple',
'data',
'python')

[56]: a=(1,2,3,4,5,6,7,8)
print(a*2)
print(a+a+a)
print(len(a))

(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)
(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)
8

34
[57]: #write a program to take 5 input from the user and store it in a tuple
a=()
i=0
while i<=5:
num=int(input('Enter the Number:'))
a=a+(num,)
i=i+1
print(a)

Enter the Number:1


(1,)
Enter the Number:2
(1, 2)
Enter the Number:3
(1, 2, 3)
Enter the Number:4
(1, 2, 3, 4)
Enter the Number:5
(1, 2, 3, 4, 5)
Enter the Number:6
(1, 2, 3, 4, 5, 6)

16 Day-10 Dictionary (To store data in key:value pairs )


[65]: #Creating A Dictionary
#No duplicates allowed in dictionary
a={'Rizwan':'01','ID':'0512','Class':'3rd Year','Branch':'AIML'}
a

[65]: {'Rizwan': '01', 'ID': '0512', 'Class': '3rd Year', 'Branch': 'AIML'}

[66]: type(a)

[66]: dict

[75]: a['Rizwan']

[75]: '01'

[74]: a={'Rizwan':'01','ID':'0512','Class':'3rd Year','Branch':'AIML'}


print(a['Class'])

3rd Year

[76]: #length of a dictionary


print(len(a))

35
4

[77]: dict={'Id':'123ab','color':'black','year':1964,'a':[12,3,4,5,6],'b':
↪(2,3,4,5),'c':False}

dict

[77]: {'Id': '123ab',


'color': 'black',
'year': 1964,
'a': [12, 3, 4, 5, 6],
'b': (2, 3, 4, 5),
'c': False}

[80]: x={'name':'Rizwan','age':21,'country':'India'}
x['name']

[80]: 'Rizwan'

[82]: print(x['age'])

21

[85]: a=[Link]()
a

[85]: dict_keys(['name', 'age', 'country'])

[86]: b=[Link]()
b

[86]: dict_values(['Rizwan', 21, 'India'])

[88]: y={'name':'Rizwan','age':21,'country':'India'}
y['age']=20
y

[88]: {'name': 'Rizwan', 'age': 20, 'country': 'India'}

[91]: [Link]({'gender':'Male'}) #to add elements in the dictionary


y

[91]: {'name': 'Rizwan', 'age': 20, 'country': 'India', 'gender': 'Male'}

[92]: [Link]('age') #to remove elements from the dictionary pop


y

[92]: {'name': 'Rizwan', 'country': 'India', 'gender': 'Male'}

36
[95]: del y['name']
y

[95]: {'country': 'India', 'gender': 'Male'}

[98]: del y

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[98], line 1
----> 1 del y

NameError: name 'y' is not defined

[101]: x={'name':'Rizwan','age':21,'country':'India'}
[Link]()
print(x)
type(x)

{}

[101]: dict

[104]: dict1={1:10,2:20}
dict2={3:30,4:40}
dict3={5:50,6:60}
dict4={}
for d in (dict1,dict2,dict3):[Link](d)
print(dict4)

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

[106]: #create a number and square of that number in a key value pairs of dictionary
d={}
for x in range(1,16,1):
d[x]=x**2
print(d)

{1: 1}
{1: 1, 2: 4}
{1: 1, 2: 4, 3: 9}
{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

37
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121,
12: 144}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121,
12: 144, 13: 169}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121,
12: 144, 13: 169, 14: 196}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121,
12: 144, 13: 169, 14: 196, 15: 225}

[116]: #check whether a given key already exists in a dictionary


d={1:10,2:20,3:30,4:40,5:50,6:60}
def is_key_present(x):
if x in d:
print('The key is present',x)
else:
print('The Key is not present',x)

is_key_present(5)
is_key_present(7)

The key is present 5


The Key is not present 7

17 Day-11 SETS(Well Defined Collection Of distinct objects)


[117]: #Sets are unordered and immuteable or not changeable
a={'rizwan',1,2,3,4,2}
print(a,type(a))

{1, 2, 3, 4, 'rizwan'} <class 'set'>

[118]: [Link](5)
a

[118]: {1, 2, 3, 4, 5, 'rizwan'}

[119]: [Link](1)
a

[119]: {2, 3, 4, 5, 'rizwan'}

[121]: a

[121]: {2, 3, 4, 5, 'rizwan'}

38
[120]: a

[120]: {2, 3, 4, 5, 'rizwan'}

[122]: z={1,2,3,4,"Rizwan",'Shaikh'}
z

[122]: {1, 2, 3, 4, 'Rizwan', 'Shaikh'}

[123]: type(z)

[123]: set

[125]: [Link](10)
z

[125]: {1, 10, 2, 3, 4, 'Rizwan', 'Shaikh'}

[128]: [Link](3)
z

[128]: {1, 10, 4, 'Rizwan', 'Shaikh'}

[129]: del z

[130]: z

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[130], line 1
----> 1 z

NameError: name 'z' is not defined

[131]: #sets items are not ordered


a={'animal','balls','playground'}
print(a)

{'animal', 'playground', 'balls'}

[132]: #no Duplicates


a={'cat','cat','balls','balls'}
a

[132]: {'balls', 'cat'}

39
[133]: #True and 1 is consider same value
z={1,2,3,4,"Rizwan",'Shaikh',True}
z

[133]: {1, 2, 3, 4, 'Rizwan', 'Shaikh'}

[134]: z

[134]: {1, 2, 3, 4, 'Rizwan', 'Shaikh'}

[135]: #get the length of a set


len(a)

[135]: 2

[136]: len(z)

[136]: 6

18 set items-Data type


[137]: x1={1,2,3,4,5}
x2={1.1,2.2,3.3,4.4}
x3={'a','b','c','d'}
x4={True,False}
print(x1,x2,x3,x4)

{1, 2, 3, 4, 5} {1.1, 2.2, 3.3, 4.4} {'d', 'c', 'a', 'b'} {False, True}

[139]: x1

[139]: {1, 2, 3, 4, 5}

[141]: x5={(1,2,3,4)}
x5

[141]: {(1, 2, 3, 4)}

[146]: x6={{'a':1,'b':2}}
x6

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[146], line 1
----> 1 x6={{'a':1,'b':2}}
2 x6

40
TypeError: unhashable type: 'dict'

[147]: #The set() Constructor


thisset = set(('alpha','beta','gamma'))
print(thisset,type(thisset))

{'alpha', 'gamma', 'beta'} <class 'set'>

[152]: v={}
print(v,type(v))

{} <class 'dict'>

[153]: empty=set({})
print(empty,type(empty))

set() <class 'set'>

[154]: #Access Items


a={'a','b','c',1,2,3,4}
for i in a:
print(i)

1
2
3
4
c
a
b

[155]: #check if item is present in set or not


a={'data','python','code','datascience'}
print('code' in a)

True

[156]: print('datascience' in a)

True

[157]: print('coding ' in a)

False

[158]: print('python'in a)

41
True

[162]: #Add items


a={'a','b','c','d'}
[Link](100)
a

[162]: {100, 'a', 'b', 'c', 'd'}

[170]: x={'data','python','code'}
y={1,2,3,45,6,7,7}
[Link](y)
print(x)

{'python', 1, 2, 3, 6, 7, 45, 'data', 'code'}

[171]: #Remove elements


n={'python', 1, 2, 3, 6, 7, 45, 'data', 'code'}
[Link]('python')
n

[171]: {1, 2, 3, 45, 6, 7, 'code', 'data'}

[173]: #pop is used to reomve any elements on its own


m={'python', 1, 2, 3, 6, 7, 45, 'data', 'code'}
x=[Link]()
m

[173]: {1, 2, 3, 45, 6, 7, 'code', 'data'}

[174]: m={'python', 1, 2, 3, 6, 7, 45, 'data', 'code'}


[Link]()
m

[174]: set()

19 join of sets
[177]: x={'a','b','c'}
y={1,2,3,4,5,6}
z=[Link](y)
z

[177]: {1, 2, 3, 4, 5, 6, 'a', 'b', 'c'}

42
[178]: #Write a python program to find the max and min values
n={5,10,3,15,2,20}
print('Original set elements',n)
print('Maximum values of the set is ',max(n))
print('Minimum value of the set is',min(n))

Original set elements {2, 3, 20, 5, 10, 15}


Maximum values of the set is 20
Minimum value of the set is 2

[181]: #return a new set of identical items from two sets


set1={10,20,30,40,50}
set2={30,40,50,60,70}
print([Link](set2))

{40, 50, 30}

[188]: a={1,2,3,4,5,6,7,8}
print(len(a),max(a),min(a),tuple(a))

8 8 1 (1, 2, 3, 4, 5, 6, 7, 8)

[198]: #prime number program


a=int(input('Enter the first number:'))
b=int(input('Enter the second number:'))
if b<a:
print('Enter a valid input')
elif a==0 or b==1:
print('Enter a valid input')
else:
for n in range(a,b+1):
for i in range(2,n):
if n%i==0:
print(n,'Not a Prime number')
break
else:
print(n,"Its a Prime number")

Enter the first number:2


Enter the second number:15
2 Its a Prime number
3 Its a Prime number
4 Not a Prime number
5 Its a Prime number
6 Not a Prime number
7 Its a Prime number
8 Not a Prime number
9 Not a Prime number

43
10 Not a Prime number
11 Its a Prime number
12 Not a Prime number
13 Its a Prime number
14 Not a Prime number
15 Not a Prime number

20 LIBRARIES

21 Day 12 Numpy
[2]: import numpy as np
a=[1,2,45]
[Link](a)

[2]: array([ 1, 2, 45])

[4]: arr=[Link]([1,2,3,4,5,'rizwan','Shaikh'])
arr

[4]: array(['1', '2', '3', '4', '5', 'rizwan', 'Shaikh'], dtype='<U11')

[5]: type(arr)

[5]: [Link]

[7]: [Link]

[7]: (7,)

[8]: arr1=[Link]((1,2,3,4,5,6))
print(arr1)
type(arr1)

[1 2 3 4 5 6]

[8]: [Link]

Dimensions in array
[10]: #0d array
arr=[Link](20)
print(arr)
type(arr)
print([Link])

20
0

44
[12]: #1d array
aa=[Link]([1,2,3,4,5,6])
print(aa)
[Link]

[1 2 3 4 5 6]

[12]: 1

[17]: #2darray
ay=[Link]([['sjgidhjdk','hdgeidg',124],['jbiuedhjsx',1234,'gwyih']])
print(ay)
[Link]

[['sjgidhjdk' 'hdgeidg' '124']


['jbiuedhjsx' '1234' 'gwyih']]

[17]: 2

[21]: #3d array


arr=[Link]([[[1,2,3,4],[4,5,6,7],[7,8,9,10]]])
print(arr)
print([Link])
print([Link])

[[[ 1 2 3 4]
[ 4 5 6 7]
[ 7 8 9 10]]]
3
(1, 3, 4)

[23]: #create a 5 dimension array


arr5=[Link]([1,2,3,4,5],ndmin=5) #using ndmin fuction we can create a n␣
↪number of array

arr5

[23]: array([[[[[1, 2, 3, 4, 5]]]]])

Get the third sixth and 8th element from the array and get the sum of them
[24]: m=[Link]([41,87,34,56.8,39.23,90,15,10,19,56])
print('the third element of array m is',m[3])
print('the sixth element of array m is',m[6])
print('the eight element of array m is',m[8])
print('the sum of array is',m[3]+m[6]+m[8])

the third element of array m is 56.8


the sixth element of array m is 15.0

45
the eight element of array m is 19.0
the sum of array is 90.8
Get the third sixth and 8th element from the array and get the sum of them
[25]: m=[Link]([41,87,34,56.8,39.23,90,15,10,19,56])
print('the third element of array m is',m[2])
print('the sixth element of array m is',m[5])
print('the eight element of array m is',m[7])
print('the sum of array is',m[2]+m[5]+m[7])

the third element of array m is 34.0


the sixth element of array m is 90.0
the eight element of array m is 10.0
the sum of array is 134.0

[26]: arr=[Link]([[1,2,3,4,5],[6,7,8,9,10]])
print(arr)

[[ 1 2 3 4 5]
[ 6 7 8 9 10]]

[27]: arr[0,1]

[27]: 2

[28]: print('the last element of second row is ',arr[1,-1])

the last element of second row is 10

[30]: print('the sum of arr with elemnt is 5 and elemt 8 is',arr[0,4]+arr[1,2])

the sum of arr with elemnt is 5 and elemt 8 is 13


3d array
[34]: riz=[Link]([[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]])
print(riz,[Link])

[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]] 3

[36]: #access the third elemnt of the secodn array of the first array
riz[0,1,2]

[36]: 6

[38]: riz[0,1,1]

46
[38]: 5

[40]: riz[0,0]

[40]: array([1, 2, 3])

[41]: riz[0,1]

[41]: array([4, 5, 6])

[42]: riz[0,2]

[42]: array([7, 8, 9])

[43]: riz[0,3]

[43]: array([10, 11, 12])

[44]: riz[0,3,0]

[44]: 10

[45]: riz[0,2,1]

[45]: 8

22 Day 13 Advance Numpy


slicing of numpy arrays
[1]: import numpy as np

[47]: arr=[Link]([1,2,3,4,5])
arr[1:5]

[47]: array([2, 3, 4, 5])

[49]: arr[::2]

[49]: array([1, 3, 5])

slicing in 2d array
[53]: a=[Link]([[10,20,30,40,50],[60,70,80,90,100]])
print(a[1,::2])

[ 60 80 100]

47
[54]: a[0,0:3]

[54]: array([10, 20, 30])

data tpes in Numpy Numpy has some extra data types and refer to data type with one character
like i integer
i=integer b=boolean u=unsigned integer f=float c=complex float m=timedelta M=datetime
O=object S=string U=unicode string V=Fixed chunk of memory for other type(void)
checking a data type of an array
[56]: arr=[Link]([1,2,3,4,5])
[Link]

[56]: dtype('int32')

[57]: a=[Link](['a','b','c','d','e'])
[Link]

[57]: dtype('<U1')

[58]: b=[Link]([1,2,3,4,'a','b','c'])
[Link]

[58]: dtype('<U11')

Creating arrays with a defined data type


[59]: arr=[Link]([1,2,3,4,5],dtype='S')
print(arr)
print([Link])

[b'1' b'2' b'3' b'4' b'5']


|S1
Create an array with Data type 4 bytes integer
[61]: arr=[Link]([1,2,3,4,5],dtype='i4')
print(arr)
print([Link])

[1 2 3 4 5]
int32

[63]: arr1=[Link]([1,2,3,4,5],dtype='float')
print(arr1)
print([Link])

48
[1. 2. 3. 4. 5.]
float64
Numpy Shapes
The shape of an array is the number of elements in each dimensions
[65]: #print the shape of a 2D array
arr2=[Link]([[1,2,3,4,5],[6,7,8,9,10]])
print([Link])

(2, 5)

[66]: arr3=[Link]([[[1,2,3,4,5],[6,7,8,9,10]]])
print([Link])

(1, 2, 5)

[74]: [Link](9).reshape(3,3)

[74]: array([[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]])

[75]: [Link](9).reshape(3,3)

[75]: array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

[77]: [Link](3)

[77]: array([[1., 0., 0.],


[0., 1., 0.],
[0., 0., 1.]])

Joining Numpy arrays


[2]: arr1=[Link]([1,2,3,4])
arr2=[Link]([5,6,7,8])
arr=[Link]((arr1,arr2))
print(arr)

[1 2 3 4 5 6 7 8]
Join 2D array
[4]: arr1=[Link]([[1,2],[3,4]])
arr2=[Link]([[5,6],[7,8]])
arr=[Link]((arr1,arr2),axis=1)

49
print(arr)

[[1 2 5 6]
[3 4 7 8]]

[5]: arr1=[Link]([[1,2],[3,4]])
arr2=[Link]([[5,6],[7,8]])
arr=[Link]((arr1,arr2),axis=0)
print(arr)

[[1 2]
[3 4]
[5 6]
[7 8]]
Splitting Of Numpy Arrays
spliting the array in 3 parts
[6]: arr=[Link]([1,2,3,4,5,6,7,8,9])
newarr=np.array_split(arr,3)
print(newarr)

[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]


spliting in 4 parts
[7]: arr=[Link]([1,2,3,4,5,6,7,8,9])
newarr=np.array_split(arr,4)
print(newarr)

[array([1, 2, 3]), array([4, 5]), array([6, 7]), array([8, 9])]

23 Ravel and Flatten


Converts multidimensional array into 1D array
[11]: m=[Link]([[[1,2,3,],[4,5,6],[7,8,9]]])
print(m)
print('dimension is',[Link])

[[[1 2 3]
[4 5 6]
[7 8 9]]]
dimension is 3

[12]: m=[Link]([[[1,2,3,],[4,5,6],[7,8,9]]])
print(m)
print('dimension is',[Link])

50
n=[Link]()
print('now the new dimension is ',[Link])

[[[1 2 3]
[4 5 6]
[7 8 9]]]
dimension is 3
now the new dimension is 1

[15]: m=[Link]([[[1,2,3,],[4,5,6],[7,8,9]]])
print(m)
print('dimension is',[Link])
n=[Link]()
print(n)
print('now the new dimension is ',[Link])

[[[1 2 3]
[4 5 6]
[7 8 9]]]
dimension is 3
[1 2 3 4 5 6 7 8 9]
now the new dimension is 1

[14]: c=[Link]([[[[1,2,3],[78,89,25],[45,26,84]]]])
print(c)
print('the dimension is',[Link])

[[[[ 1 2 3]
[78 89 25]
[45 26 84]]]]
the dimension is 4

[16]: c=[Link]([[[[1,2,3],[78,89,25],[45,26,84]]]])
print(c)
print('the dimension is',[Link])
m=[Link]()
print(m)
print('the new dimension is',[Link])

[[[[ 1 2 3]
[78 89 25]
[45 26 84]]]]
the dimension is 4
[ 1 2 3 78 89 25 45 26 84]
the new dimension is 1
unique function

51
[17]: k=[Link]([12,1,4,6,7,9,3,4,5,22,33,7,6,9,1,2,12])
print(k)
x=[Link](k)
print(x)

[12 1 4 6 7 9 3 4 5 22 33 7 6 9 1 2 12]
[ 1 2 3 4 5 6 7 9 12 22 33]

[18]: k=[Link]([12,1,4,6,7,9,3,4,5,22,33,7,6,9,1,2,12])
print(k)
x=[Link](k,return_index=True)
print(x)

[12 1 4 6 7 9 3 4 5 22 33 7 6 9 1 2 12]
(array([ 1, 2, 3, 4, 5, 6, 7, 9, 12, 22, 33]), array([ 1, 15, 6, 2, 8,
3, 4, 5, 0, 9, 10], dtype=int64))

[19]: k=[Link]([12,1,4,6,7,9,3,4,5,22,33,7,6,9,1,2,12])
print(k)
x=[Link](k,return_counts=True)
print(x)

[12 1 4 6 7 9 3 4 5 22 33 7 6 9 1 2 12]
(array([ 1, 2, 3, 4, 5, 6, 7, 9, 12, 22, 33]), array([2, 1, 1, 2, 1, 2,
2, 2, 2, 1, 1], dtype=int64))
Delete
[20]: a=[Link]([12,13,14,15])
d=[Link](a,[1])
d

[20]: array([12, 14, 15])

[21]: x=[Link]([[2,7,9,6,8],[4,5,7,1,2],[50,0,65,6,7]])
print(x)

[[ 2 7 9 6 8]
[ 4 5 7 1 2]
[50 0 65 6 7]]

[22]: x=[Link]([[2,7,9,6,8],[4,5,7,1,2],[50,0,65,6,7]])
print(x)
m=[Link](x,1,axis=0)
print(m)

[[ 2 7 9 6 8]
[ 4 5 7 1 2]
[50 0 65 6 7]]

52
[[ 2 7 9 6 8]
[50 0 65 6 7]]

24 Day-14 Pandas
[23]: import pandas as pd

[34]: df=pd.read_csv('[Link]')
[Link](20)

[34]: PassengerId Survived Pclass \


0 1 0 3
1 2 1 1
2 3 1 3
3 4 1 1
4 5 0 3
5 6 0 3
6 7 0 1
7 8 0 3
8 9 1 3
9 10 1 2
10 11 1 3
11 12 1 1
12 13 0 3
13 14 0 3
14 15 0 3
15 16 1 2
16 17 0 3
17 18 1 2
18 19 0 3
19 20 1 3

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
5 Moran, Mr. James male NaN 0
6 McCarthy, Mr. Timothy J male 54.0 0
7 Palsson, Master. Gosta Leonard male 2.0 3
8 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0 0
9 Nasser, Mrs. Nicholas (Adele Achem) female 14.0 1
10 Sandstrom, Miss. Marguerite Rut female 4.0 1
11 Bonnell, Miss. Elizabeth female 58.0 0
12 Saundercock, Mr. William Henry male 20.0 0
13 Andersson, Mr. Anders Johan male 39.0 1

53
14 Vestrom, Miss. Hulda Amanda Adolfina female 14.0 0
15 Hewlett, Mrs. (Mary D Kingcome) female 55.0 0
16 Rice, Master. Eugene male 2.0 4
17 Williams, Mr. Charles Eugene male NaN 0
18 Vander Planke, Mrs. Julius (Emelia Maria Vande… female 31.0 1
19 Masselmani, Mrs. Fatima female NaN 0

Parch Ticket Fare Cabin Embarked


0 0 A/5 21171 7.2500 NaN S
1 0 PC 17599 71.2833 C85 C
2 0 STON/O2. 3101282 7.9250 NaN S
3 0 113803 53.1000 C123 S
4 0 373450 8.0500 NaN S
5 0 330877 8.4583 NaN Q
6 0 17463 51.8625 E46 S
7 1 349909 21.0750 NaN S
8 2 347742 11.1333 NaN S
9 0 237736 30.0708 NaN C
10 1 PP 9549 16.7000 G6 S
11 0 113783 26.5500 C103 S
12 0 A/5. 2151 8.0500 NaN S
13 5 347082 31.2750 NaN S
14 0 350406 7.8542 NaN S
15 0 248706 16.0000 NaN S
16 1 382652 29.1250 NaN Q
17 0 244373 13.0000 NaN S
18 0 345763 18.0000 NaN S
19 0 2649 7.2250 NaN C

[35]: [Link](20)

[35]: PassengerId Survived Pclass \


871 872 1 1
872 873 0 1
873 874 0 3
874 875 1 2
875 876 1 3
876 877 0 3
877 878 0 3
878 879 0 3
879 880 1 1
880 881 1 2
881 882 0 3
882 883 0 3
883 884 0 2
884 885 0 3
885 886 0 3

54
886 887 0 2
887 888 1 1
888 889 0 3
889 890 1 1
890 891 0 3

Name Sex Age SibSp \


871 Beckwith, Mrs. Richard Leonard (Sallie Monypeny) female 47.0 1
872 Carlsson, Mr. Frans Olof male 33.0 0
873 Vander Cruyssen, Mr. Victor male 47.0 0
874 Abelson, Mrs. Samuel (Hannah Wizosky) female 28.0 1
875 Najib, Miss. Adele Kiamie "Jane" female 15.0 0
876 Gustafsson, Mr. Alfred Ossian male 20.0 0
877 Petroff, Mr. Nedelio male 19.0 0
878 Laleff, Mr. Kristo male NaN 0
879 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson) female 56.0 0
880 Shelley, Mrs. William (Imanita Parrish Hall) female 25.0 0
881 Markun, Mr. Johann male 33.0 0
882 Dahlberg, Miss. Gerda Ulrika female 22.0 0
883 Banfield, Mr. Frederick James male 28.0 0
884 Sutehall, Mr. Henry Jr male 25.0 0
885 Rice, Mrs. William (Margaret Norton) female 39.0 0
886 Montvila, Rev. Juozas male 27.0 0
887 Graham, Miss. Margaret Edith female 19.0 0
888 Johnston, Miss. Catherine Helen "Carrie" female NaN 1
889 Behr, Mr. Karl Howell male 26.0 0
890 Dooley, Mr. Patrick male 32.0 0

Parch Ticket Fare Cabin Embarked


871 1 11751 52.5542 D35 S
872 0 695 5.0000 B51 B53 B55 S
873 0 345765 9.0000 NaN S
874 0 P/PP 3381 24.0000 NaN C
875 0 2667 7.2250 NaN C
876 0 7534 9.8458 NaN S
877 0 349212 7.8958 NaN S
878 0 349217 7.8958 NaN S
879 1 11767 83.1583 C50 C
880 1 230433 26.0000 NaN S
881 0 349257 7.8958 NaN S
882 0 7552 10.5167 NaN S
883 0 C.A./SOTON 34068 10.5000 NaN S
884 0 SOTON/OQ 392076 7.0500 NaN S
885 5 382652 29.1250 NaN Q
886 0 211536 13.0000 NaN S
887 0 112053 30.0000 B42 S
888 2 W./C. 6607 23.4500 NaN S

55
889 0 111369 30.0000 C148 C
890 0 370376 7.7500 NaN Q

[36]: [Link]

[36]: PassengerId int64


Survived int64
Pclass int64
Name object
Sex object
Age float64
SibSp int64
Parch int64
Ticket object
Fare float64
Cabin object
Embarked object
dtype: object

[39]: [Link]()

[39]: PassengerId Survived Pclass Age SibSp \


count 891.000000 891.000000 891.000000 714.000000 891.000000
mean 446.000000 0.383838 2.308642 29.699118 0.523008
std 257.353842 0.486592 0.836071 14.526497 1.102743
min 1.000000 0.000000 1.000000 0.420000 0.000000
25% 223.500000 0.000000 2.000000 20.125000 0.000000
50% 446.000000 0.000000 3.000000 28.000000 0.000000
75% 668.500000 1.000000 3.000000 38.000000 1.000000
max 891.000000 1.000000 3.000000 80.000000 8.000000

Parch Fare
count 891.000000 891.000000
mean 0.381594 32.204208
std 0.806057 49.693429
min 0.000000 0.000000
25% 0.000000 7.910400
50% 0.000000 14.454200
75% 0.000000 31.000000
max 6.000000 512.329200

[46]: df[['Name','Sex','Ticket','Cabin','Embarked']]

[46]: Name Sex \


0 Braund, Mr. Owen Harris male
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female
2 Heikkinen, Miss. Laina female

56
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female
4 Allen, Mr. William Henry male
.. … …
886 Montvila, Rev. Juozas male
887 Graham, Miss. Margaret Edith female
888 Johnston, Miss. Catherine Helen "Carrie" female
889 Behr, Mr. Karl Howell male
890 Dooley, Mr. Patrick male

Ticket Cabin Embarked


0 A/5 21171 NaN S
1 PC 17599 C85 C
2 STON/O2. 3101282 NaN S
3 113803 C123 S
4 373450 NaN S
.. … … …
886 211536 NaN S
887 112053 B42 S
888 W./C. 6607 NaN S
889 111369 C148 C
890 370376 NaN Q

[891 rows x 5 columns]

[48]: [Link]=='object'

[48]: PassengerId False


Survived False
Pclass False
Name True
Sex True
Age False
SibSp False
Parch False
Ticket True
Fare False
Cabin True
Embarked True
dtype: bool

[49]: [Link]=='float64'

[49]: PassengerId False


Survived False
Pclass False
Name False
Sex False

57
Age True
SibSp False
Parch False
Ticket False
Fare True
Cabin False
Embarked False
dtype: bool

[51]: [Link]=='int64'

[51]: PassengerId True


Survived True
Pclass True
Name False
Sex False
Age False
SibSp True
Parch True
Ticket False
Fare False
Cabin False
Embarked False
dtype: bool

[53]: df[[Link][[Link]=='float64'].index]

[53]: Age Fare


0 22.0 7.2500
1 38.0 71.2833
2 26.0 7.9250
3 35.0 53.1000
4 35.0 8.0500
.. … …
886 27.0 13.0000
887 19.0 30.0000
888 NaN 23.4500
889 26.0 30.0000
890 32.0 7.7500

[891 rows x 2 columns]

[54]: df[[Link][[Link]=='int64'].index]

[54]: PassengerId Survived Pclass SibSp Parch


0 1 0 3 1 0
1 2 1 1 1 0

58
2 3 1 3 0 0
3 4 1 1 1 0
4 5 0 3 0 0
.. … … … … …
886 887 0 2 0 0
887 888 1 1 0 0
888 889 0 3 1 2
889 890 1 1 0 0
890 891 0 3 0 0

[891 rows x 5 columns]

[55]: [Link]

[55]: Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',


'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
dtype='object')

[58]: df[['Ticket']]

[58]: Ticket
0 A/5 21171
1 PC 17599
2 STON/O2. 3101282
3 113803
4 373450
.. …
886 211536
887 112053
888 W./C. 6607
889 111369
890 370376

[891 rows x 1 columns]

[59]: df[['Ticket']][4:16:2]

[59]: Ticket
4 373450
6 17463
8 347742
10 PP 9549
12 A/5. 2151
14 350406

[60]: df[['Ticket','Cabin']]

59
[60]: Ticket Cabin
0 A/5 21171 NaN
1 PC 17599 C85
2 STON/O2. 3101282 NaN
3 113803 C123
4 373450 NaN
.. … …
886 211536 NaN
887 112053 B42
888 W./C. 6607 NaN
889 111369 C148
890 370376 NaN

[891 rows x 2 columns]

[61]: df[['Ticket','Cabin']][4:17]

[61]: Ticket Cabin


4 373450 NaN
5 330877 NaN
6 17463 E46
7 349909 NaN
8 347742 NaN
9 237736 NaN
10 PP 9549 G6
11 113783 C103
12 A/5. 2151 NaN
13 347082 NaN
14 350406 NaN
15 248706 NaN
16 382652 NaN

[62]: df[['Ticket','Cabin']][:17:2]

[62]: Ticket Cabin


0 A/5 21171 NaN
2 STON/O2. 3101282 NaN
4 373450 NaN
6 17463 E46
8 347742 NaN
10 PP 9549 G6
12 A/5. 2151 NaN
14 350406 NaN
16 382652 NaN

[64]: df['New_Col']=0

60
[66]: [Link](10)

[66]: PassengerId Survived Pclass \


0 1 0 3
1 2 1 1
2 3 1 3
3 4 1 1
4 5 0 3
5 6 0 3
6 7 0 1
7 8 0 3
8 9 1 3
9 10 1 2

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
5 Moran, Mr. James male NaN 0
6 McCarthy, Mr. Timothy J male 54.0 0
7 Palsson, Master. Gosta Leonard male 2.0 3
8 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0 0
9 Nasser, Mrs. Nicholas (Adele Achem) female 14.0 1

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0
5 0 330877 8.4583 NaN Q 0
6 0 17463 51.8625 E46 S 0
7 1 349909 21.0750 NaN S 0
8 2 347742 11.1333 NaN S 0
9 0 237736 30.0708 NaN C 0

[67]: [Link](loc=3,column='Food',value=0)

[68]: df

[68]: PassengerId Survived Pclass Food \


0 1 0 3 0
1 2 1 1 0
2 3 1 3 0
3 4 1 1 0

61
4 5 0 3 0
.. … … … …
886 887 0 2 0
887 888 1 1 0
888 889 0 3 0
889 890 1 1 0
890 891 0 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
.. … … … …
886 Montvila, Rev. Juozas male 27.0 0
887 Graham, Miss. Margaret Edith female 19.0 0
888 Johnston, Miss. Catherine Helen "Carrie" female NaN 1
889 Behr, Mr. Karl Howell male 26.0 0
890 Dooley, Mr. Patrick male 32.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0
.. … … … … … …
886 0 211536 13.0000 NaN S 0
887 0 112053 30.0000 B42 S 0
888 2 W./C. 6607 23.4500 NaN S 0
889 0 111369 30.0000 C148 C 0
890 0 370376 7.7500 NaN Q 0

[891 rows x 14 columns]

25 Day-15 Advance Pandas


[69]: df['Name']

[69]: 0 Braund, Mr. Owen Harris


1 Cumings, Mrs. John Bradley (Florence Briggs Th…
2 Heikkinen, Miss. Laina
3 Futrelle, Mrs. Jacques Heath (Lily May Peel)
4 Allen, Mr. William Henry

62
886 Montvila, Rev. Juozas
887 Graham, Miss. Margaret Edith
888 Johnston, Miss. Catherine Helen "Carrie"
889 Behr, Mr. Karl Howell
890 Dooley, Mr. Patrick
Name: Name, Length: 891, dtype: object

[73]: a=df['Name'][0:10]

[75]: a

[75]: 0 Braund, Mr. Owen Harris


1 Cumings, Mrs. John Bradley (Florence Briggs Th…
2 Heikkinen, Miss. Laina
3 Futrelle, Mrs. Jacques Heath (Lily May Peel)
4 Allen, Mr. William Henry
5 Moran, Mr. James
6 McCarthy, Mr. Timothy J
7 Palsson, Master. Gosta Leonard
8 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)
9 Nasser, Mrs. Nicholas (Adele Achem)
Name: Name, dtype: object

[74]: l=['rizwan','a2','a3','a4','a5','a6','a7','a8','a9','a10']

[76]: [Link](a,index=l)

[76]: rizwan NaN


a2 NaN
a3 NaN
a4 NaN
a5 NaN
a6 NaN
a7 NaN
a8 NaN
a9 NaN
a10 NaN
Name: Name, dtype: object

[77]: [Link](list(a),index=l)

[77]: rizwan Braund, Mr. Owen Harris


a2 Cumings, Mrs. John Bradley (Florence Briggs Th…
a3 Heikkinen, Miss. Laina
a4 Futrelle, Mrs. Jacques Heath (Lily May Peel)
a5 Allen, Mr. William Henry
a6 Moran, Mr. James

63
a7 McCarthy, Mr. Timothy J
a8 Palsson, Master. Gosta Leonard
a9 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)
a10 Nasser, Mrs. Nicholas (Adele Achem)
dtype: object

[78]: m1=[Link]([100,200,300,400,500],index=[1,2,3,4,5])
m1

[78]: 1 100
2 200
3 300
4 400
5 500
dtype: int64

[79]: m2=[Link]([600,700,800,900],index=[6,7,8,9])
m2

[79]: 6 600
7 700
8 800
9 900
dtype: int64

[80]: m3=[Link]([m1,m2])
m3

[80]: 1 100
2 200
3 300
4 400
5 500
6 600
7 700
8 800
9 900
dtype: int64

[81]: m3[1]

[81]: 100

[82]: m1*m2

[82]: 1 NaN
2 NaN

64
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
dtype: float64

[83]: m1+m2

[83]: 1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
dtype: float64

[84]: [Link]()

[84]: PassengerId Survived Pclass Food \


0 1 0 3 0
1 2 1 1 0
2 3 1 3 0
3 4 1 1 0
4 5 0 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0

[88]: [Link]('PassengerId',axis=1).head()

65
[88]: Survived Pclass Food Name \
0 0 3 0 Braund, Mr. Owen Harris
1 1 1 0 Cumings, Mrs. John Bradley (Florence Briggs Th…
2 1 3 0 Heikkinen, Miss. Laina
3 1 1 0 Futrelle, Mrs. Jacques Heath (Lily May Peel)
4 0 3 0 Allen, Mr. William Henry

Sex Age SibSp Parch Ticket Fare Cabin Embarked \


0 male 22.0 1 0 A/5 21171 7.2500 NaN S
1 female 38.0 1 0 PC 17599 71.2833 C85 C
2 female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 female 35.0 1 0 113803 53.1000 C123 S
4 male 35.0 0 0 373450 8.0500 NaN S

New_Col
0 0
1 0
2 0
3 0
4 0

[89]: [Link]()

[89]: PassengerId Survived Pclass Food \


0 1 0 3 0
1 2 1 1 0
2 3 1 3 0
3 4 1 1 0
4 5 0 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0

[93]: [Link]('Survived',axis=1,inplace=True) #inplace=True is used to delete the␣


↪entire row or columns from the main dataset

66
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[93], line 1
----> 1 [Link]('Survived',axis=1,inplace=True)

File ~\anaconda3\Lib\site-packages\pandas\core\[Link], in DataFrame.


↪drop(self, labels, axis, index, columns, level, inplace, errors)

5110 def drop(


5111 self,
5112 labels: IndexLabel = None,
(…)
5119 errors: IgnoreRaise = "raise",
5120 ) -> DataFrame | None:
5121 """
5122 Drop specified labels from rows or columns.
5123
(…)
5256 weight 1.0 0.8
5257 """
-> 5258 return super().drop(
5259 labels=labels,
5260 axis=axis,
5261 index=index,
5262 columns=columns,
5263 level=level,
5264 inplace=inplace,
5265 errors=errors,
5266 )

File ~\anaconda3\Lib\site-packages\pandas\core\[Link], in NDFrame.


↪drop(self, labels, axis, index, columns, level, inplace, errors)

4547 for axis, labels in [Link]():


4548 if labels is not None:
-> 4549 obj = obj._drop_axis(labels, axis, level=level, errors=errors)
4551 if inplace:
4552 self._update_inplace(obj)

File ~\anaconda3\Lib\site-packages\pandas\core\[Link], in NDFrame.


↪_drop_axis(self, labels, axis, level, errors, only_slice)

4589 new_axis = [Link](labels, level=level, errors=errors)


4590 else:
-> 4591 new_axis = [Link](labels, errors=errors)
4592 indexer = axis.get_indexer(new_axis)
4594 # Case for non-unique axis
4595 else:

67
File ~\anaconda3\Lib\site-packages\pandas\core\indexes\[Link], in Index.
↪drop(self, labels, errors)

6697 if [Link]():
6698 if errors != "ignore":
-> 6699 raise KeyError(f"{list(labels[mask])} not found in axis")
6700 indexer = indexer[~mask]
6701 return [Link](indexer)

KeyError: "['Survived'] not found in axis"

[92]: df

[92]: PassengerId Pclass Food \


0 1 3 0
1 2 1 0
2 3 3 0
3 4 1 0
4 5 3 0
.. … … …
886 887 2 0
887 888 1 0
888 889 3 0
889 890 1 0
890 891 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
.. … … … …
886 Montvila, Rev. Juozas male 27.0 0
887 Graham, Miss. Margaret Edith female 19.0 0
888 Johnston, Miss. Catherine Helen "Carrie" female NaN 1
889 Behr, Mr. Karl Howell male 26.0 0
890 Dooley, Mr. Patrick male 32.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0
.. … … … … … …
886 0 211536 13.0000 NaN S 0
887 0 112053 30.0000 B42 S 0

68
888 2 W./C. 6607 23.4500 NaN S 0
889 0 111369 30.0000 C148 C 0
890 0 370376 7.7500 NaN Q 0

[891 rows x 13 columns]

[94]: [Link](3)

[94]: PassengerId Pclass Food \


0 1 3 0
1 2 1 0
2 3 3 0
4 5 3 0
5 6 3 0
.. … … …
886 887 2 0
887 888 1 0
888 889 3 0
889 890 1 0
890 891 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
4 Allen, Mr. William Henry male 35.0 0
5 Moran, Mr. James male NaN 0
.. … … … …
886 Montvila, Rev. Juozas male 27.0 0
887 Graham, Miss. Margaret Edith female 19.0 0
888 Johnston, Miss. Catherine Helen "Carrie" female NaN 1
889 Behr, Mr. Karl Howell male 26.0 0
890 Dooley, Mr. Patrick male 32.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
4 0 373450 8.0500 NaN S 0
5 0 330877 8.4583 NaN Q 0
.. … … … … … …
886 0 211536 13.0000 NaN S 0
887 0 112053 30.0000 B42 S 0
888 2 W./C. 6607 23.4500 NaN S 0
889 0 111369 30.0000 C148 C 0
890 0 370376 7.7500 NaN Q 0

69
[890 rows x 13 columns]

[95]: df.set_index('Name')

[95]: PassengerId Pclass Food \


Name
Braund, Mr. Owen Harris 1 3 0
Cumings, Mrs. John Bradley (Florence Briggs Tha… 2 1 0
Heikkinen, Miss. Laina 3 3 0
Futrelle, Mrs. Jacques Heath (Lily May Peel) 4 1 0
Allen, Mr. William Henry 5 3 0
… … … …
Montvila, Rev. Juozas 887 2 0
Graham, Miss. Margaret Edith 888 1 0
Johnston, Miss. Catherine Helen "Carrie" 889 3 0
Behr, Mr. Karl Howell 890 1 0
Dooley, Mr. Patrick 891 3 0

Sex Age SibSp \


Name
Braund, Mr. Owen Harris male 22.0 1
Cumings, Mrs. John Bradley (Florence Briggs Tha… female 38.0 1
Heikkinen, Miss. Laina female 26.0 0
Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
Allen, Mr. William Henry male 35.0 0
… … … …
Montvila, Rev. Juozas male 27.0 0
Graham, Miss. Margaret Edith female 19.0 0
Johnston, Miss. Catherine Helen "Carrie" female NaN 1
Behr, Mr. Karl Howell male 26.0 0
Dooley, Mr. Patrick male 32.0 0

Parch Ticket \
Name
Braund, Mr. Owen Harris 0 A/5 21171
Cumings, Mrs. John Bradley (Florence Briggs Tha… 0 PC 17599
Heikkinen, Miss. Laina 0 STON/O2. 3101282
Futrelle, Mrs. Jacques Heath (Lily May Peel) 0 113803
Allen, Mr. William Henry 0 373450
… … …
Montvila, Rev. Juozas 0 211536
Graham, Miss. Margaret Edith 0 112053
Johnston, Miss. Catherine Helen "Carrie" 2 W./C. 6607
Behr, Mr. Karl Howell 0 111369
Dooley, Mr. Patrick 0 370376

Fare Cabin Embarked \

70
Name
Braund, Mr. Owen Harris 7.2500 NaN S
Cumings, Mrs. John Bradley (Florence Briggs Tha… 71.2833 C85 C
Heikkinen, Miss. Laina 7.9250 NaN S
Futrelle, Mrs. Jacques Heath (Lily May Peel) 53.1000 C123 S
Allen, Mr. William Henry 8.0500 NaN S
… … … …
Montvila, Rev. Juozas 13.0000 NaN S
Graham, Miss. Margaret Edith 30.0000 B42 S
Johnston, Miss. Catherine Helen "Carrie" 23.4500 NaN S
Behr, Mr. Karl Howell 30.0000 C148 C
Dooley, Mr. Patrick 7.7500 NaN Q

New_Col
Name
Braund, Mr. Owen Harris 0
Cumings, Mrs. John Bradley (Florence Briggs Tha… 0
Heikkinen, Miss. Laina 0
Futrelle, Mrs. Jacques Heath (Lily May Peel) 0
Allen, Mr. William Henry 0
… …
Montvila, Rev. Juozas 0
Graham, Miss. Margaret Edith 0
Johnston, Miss. Catherine Helen "Carrie" 0
Behr, Mr. Karl Howell 0
Dooley, Mr. Patrick 0

[891 rows x 12 columns]

[96]: df.reset_index()

[96]: index PassengerId Pclass Food \


0 0 1 3 0
1 1 2 1 0
2 2 3 3 0
3 3 4 1 0
4 4 5 3 0
.. … … … …
886 886 887 2 0
887 887 888 1 0
888 888 889 3 0
889 889 890 1 0
890 890 891 3 0

Name Sex Age SibSp \


0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1

71
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
.. … … … …
886 Montvila, Rev. Juozas male 27.0 0
887 Graham, Miss. Margaret Edith female 19.0 0
888 Johnston, Miss. Catherine Helen "Carrie" female NaN 1
889 Behr, Mr. Karl Howell male 26.0 0
890 Dooley, Mr. Patrick male 32.0 0

Parch Ticket Fare Cabin Embarked New_Col


0 0 A/5 21171 7.2500 NaN S 0
1 0 PC 17599 71.2833 C85 C 0
2 0 STON/O2. 3101282 7.9250 NaN S 0
3 0 113803 53.1000 C123 S 0
4 0 373450 8.0500 NaN S 0
.. … … … … … …
886 0 211536 13.0000 NaN S 0
887 0 112053 30.0000 B42 S 0
888 2 W./C. 6607 23.4500 NaN S 0
889 0 111369 30.0000 C148 C 0
890 0 370376 7.7500 NaN Q 0

[891 rows x 14 columns]

[100]: d={'keys':[1,2,3,4,5],'key2':[6,7,8,9,10],'key3':[11,12,13,14,15]}
d

[100]: {'keys': [1, 2, 3, 4, 5],


'key2': [6, 7, 8, 9, 10],
'key3': [11, 12, 13, 14, 15]}

[101]: [Link](d)

[101]: keys key2 key3


0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15

26 Day16 MatPlotlib
A Multi-platform data visualization library built on Numpy Arrays and Designed to work with the
broader SciPy Stack
[102]: import [Link] as plt

72
Linear graph
[104]: x=[1,2,3,4]
y=[5,6,7,8]
[Link](x,y)
[Link]()

[105]: x=[1,2,3,4]
y=[5,6,7,8]
c='r'
[Link](x,y,c)
[Link]()

73
[107]: x=[5,2,9,4,7]
y=[10,5,8,4,2]
c='y'
[Link](x,y,c)

[107]: [<[Link].Line2D at 0x27a51e6c750>]

74
[110]: x=[5,2,9,4,7]
y=[10,5,8,4,2]
c='y'
[Link](x,y,c,marker='o')

[110]: [<[Link].Line2D at 0x27a56330590>]

75
[115]: x=[5,2,9,4,7]
y=[10,5,8,4,2]
[Link](x,y,marker='o')
[Link](y,marker='>')
[Link](x,marker='*')
[Link]()

76
Bar Graph
[116]: x=[1,2,3,4,5]
y=[6,7,8,9,10]
[Link](x,y)
[Link]()

77
[122]: x=[1,2,3,4,5]
y=[6,7,8,9,10]
c=['r','g','y']
[Link](x,y,color=c)
[Link]()

78
[123]: import numpy as np

[125]: x=[Link](['A','B','C','D']) #h represent the horizontal direction of the graph


y=[Link]([3,8,1,10])
c=['r','g','y','b']
[Link](x,y,color=c)

[125]: <BarContainer object of 4 artists>

79
[134]: x=[Link](10,20,6)
y=[Link](1,10,6)
[Link](x,y,color='red')

[134]: <BarContainer object of 6 artists>

80
[136]: x=[Link](['A','B','C','D']) #width for only bar graph
y=[Link]([3,8,1,10])
c=['r','g','y','b']
[Link](x,y,color=c,width=0.1)

[136]: <BarContainer object of 4 artists>

81
[137]: x=[Link](['A','B','C','D']) #height is for barh graph
y=[Link]([3,8,1,10])
c=['r','g','y','b']
[Link](x,y,color=c,height=0.1)

[137]: <BarContainer object of 4 artists>

82
[ ]: #To create a chart pyplot provided
#ans=plot()

Scatter Plot
[157]: import [Link] as plt

[169]: x=[1,2,3,4,5,6]
y=[4,2,3,5,1,8]
[Link]('Month')
[Link]('numbers')
[Link](x,y)
[Link]()

83
[170]: x=[1,2,3,4,5,6]
y=[4,2,3,5,1,8]
[Link]('Month')
[Link]('numbers')
[Link](x,y,color='red')
[Link]()

84
[175]: x=[1,2,3,4,5,6]
y=[4,2,3,5,1,8]
[Link]('Month')
[Link]('numbers')
c=['red','yellow','magenta','orange','blue','brown']
[Link](x,y,color=c)
[Link]()

85
[176]: x=[1,2,3,4,5,6] #s is for size
y=[4,2,3,5,1,8]
[Link]('Month')
[Link]('numbers')
[Link](x,y,s=150)
[Link]()

86
27 Day 17 Part 2 Matplotlib
[2]: import [Link] as plt

[8]: #importing libraries


import numpy as np
import [Link] as plt
from PIL import Image

fname=r'[Link]'

#opening image using pil

image=[Link](fname).convert('L')

#mapping image to gray scale


[Link](image,cmap='gray')
[Link]()

87
[11]: import numpy as np
import [Link] as plt
from PIL import Image

fname=r'[Link]'

image=[Link](fname).convert('L')

[Link](image,cmap='gray')
[Link]()

88
# All the colors in cmap
‘g’ is not a valid value for cmap; supported values are ‘Accent’, ‘Accent_r’, ‘Blues’,
‘Blues_r’, ‘BrBG’, ‘BrBG_r’, ‘BuGn’, ‘BuGn_r’, ‘BuPu’, ‘BuPu_r’, ‘CMRmap’, ‘CM-
Rmap_r’, ‘Dark2’, ‘Dark2_r’, ‘GnBu’, ‘GnBu_r’, ‘Greens’, ‘Greens_r’, ‘Greys’, ‘Greys_r’,
‘OrRd’, ‘OrRd_r’, ‘Oranges’, ‘Oranges_r’, ‘PRGn’, ‘PRGn_r’, ‘Paired’, ‘Paired_r’, ‘Pas-
tel1’, ‘Pastel1_r’, ‘Pastel2’, ‘Pastel2_r’, ‘PiYG’, ‘PiYG_r’, ‘PuBu’, ‘PuBuGn’, ‘PuBuGn_r’,
‘PuBu_r’, ‘PuOr’, ‘PuOr_r’, ‘PuRd’, ‘PuRd_r’, ‘Purples’, ‘Purples_r’, ‘RdBu’, ‘RdBu_r’,
‘RdGy’, ‘RdGy_r’, ‘RdPu’, ‘RdPu_r’, ‘RdYlBu’, ‘RdYlBu_r’, ‘RdYlGn’, ‘RdYlGn_r’, ‘Reds’,
‘Reds_r’, ‘Set1’, ‘Set1_r’, ‘Set2’, ‘Set2_r’, ‘Set3’, ‘Set3_r’, ‘Spectral’, ‘Spectral_r’, ‘Wis-
tia’, ‘Wistia_r’, ‘YlGn’, ‘YlGnBu’, ‘YlGnBu_r’, ‘YlGn_r’, ‘YlOrBr’, ‘YlOrBr_r’, ‘YlOrRd’,
‘YlOrRd_r’, ‘afmhot’, ‘afmhot_r’, ‘autumn’, ‘autumn_r’, ‘binary’, ‘binary_r’, ‘bone’, ‘bone_r’,
‘brg’, ‘brg_r’, ‘bwr’, ‘bwr_r’, ‘cividis’, ‘cividis_r’, ‘cool’, ‘cool_r’, ‘coolwarm’, ‘coolwarm_r’,
‘copper’, ‘copper_r’, ‘cubehelix’, ‘cubehelix_r’, ‘flag’, ‘flag_r’, ‘gist_earth’, ‘gist_earth_r’,
‘gist_gray’, ‘gist_gray_r’, ‘gist_heat’, ‘gist_heat_r’, ‘gist_ncar’, ‘gist_ncar_r’, ‘gist_rainbow’,
‘gist_rainbow_r’, ‘gist_stern’, ‘gist_stern_r’, ‘gist_yarg’, ‘gist_yarg_r’, ‘gnuplot’, ‘gnuplot2’,
‘gnuplot2_r’, ‘gnuplot_r’, ‘gray’, ‘gray_r’, ‘hot’, ‘hot_r’, ‘hsv’, ‘hsv_r’, ‘inferno’, ‘inferno_r’,
‘jet’, ‘jet_r’, ‘magma’, ‘magma_r’, ‘nipy_spectral’, ‘nipy_spectral_r’, ‘ocean’, ‘ocean_r’, ‘pink’,
‘pink_r’, ‘plasma’, ‘plasma_r’, ‘prism’, ‘prism_r’, ‘rainbow’, ‘rainbow_r’, ‘seismic’, ‘seismic_r’,
‘spring’, ‘spring_r’, ‘summer’, ‘summer_r’, ‘tab10’, ‘tab10_r’, ‘tab20’, ‘tab20_r’, ‘tab20b’,
‘tab20b_r’, ‘tab20c’, ‘tab20c_r’, ‘terrain’, ‘terrain_r’, ‘turbo’, ‘turbo_r’, ‘twilight’, ‘twilight_r’,
‘twilight_shifted’, ‘twilight_shifted_r’, ‘viridis’, ‘viridis_r’, ‘winter’, ’winter_r

89
[15]: import numpy as np
import [Link] as plt
from PIL import Image

fname=r'[Link]'

image=[Link](fname).convert('L')

[Link](image,cmap= 'copper')
[Link]()

[18]: import numpy as np


import [Link] as plt
from PIL import Image
fname=r'[Link]'
image=[Link](fname).convert('L')
[Link](image,cmap='gray')
[Link]()

90
[23]: import numpy as np #Save Fig is used to save the pics␣
↪Savefig()

import [Link] as plt


from PIL import Image
fname=r'[Link]'
image=[Link](fname).convert('L')
[Link](image,cmap='flag')
[Link]('Rose pic')
[Link]('Length')
[Link]('Breadth')
[Link]()
[Link]()

91
Pie Chart
[24]: import [Link] as plt

[30]: x=[10,20,30,40,50]
y=['English','Hindi','Science','Maths','SocialScience']
c=['yellow','magenta','brown','red','blue']
[Link](x,labels=y,colors=c)
[Link]()

92
[32]: x=[10,20,30,40,50]
y=['English','Hindi','Science','Maths','SocialScience']
c=['yellow','magenta','brown','red','blue']
[Link](x,labels=y,colors=c)
[Link]()
[Link]()

93
28 Day-18 Seaborn Library
[ ]: #why seaborn library
#Seaborn is a library for making statisticl graphs in python (mean,median)
#integrated on pandas and matplotlib
#relational plot-it is used to understand the relation between the two variables
#categorical plot-deals with categorical variables and how they can be␣
↪visualized

#distribution plot-This plot is used for examining univariate and bivariate␣


↪distribution

#regression plot-to plot the regression of data points


#matrix plot-it is a plot of arrays of scatter plots
#multiplot-multiple plot

[59]: import numpy as np


import pandas as pd
import [Link] as plt
import seaborn as sns

[61]: var=[1,2,3,4,5,6,7,8]
var1=[8,7,6,5,4,3,2,1]

94
[46]: #matplotlib
[Link](var,var1)
[Link]()

[62]: #Seaborn
[Link](x=var,y=var1)

[62]: <Axes: >

95
[63]: var=[1,2,3,4,5,6,7,8]
var1=[8,7,6,5,4,3,2,1]
import pandas as pd
df=[Link]({'var':var,'var1':var1})
[Link](x='var',y='var1',data=df)

[63]: <Axes: xlabel='var', ylabel='var1'>

96
[49]: df

[49]: var var1


0 1 8
1 2 7
2 3 6
3 4 5
4 5 4
5 6 3
6 7 2
7 8 1

[ ]: # Bootstrap plots are used to visually show the assess the uncertanity of a␣
↪statistic

[64]: df1=sns.load_dataset('penguins')

[65]: df1

[65]: species island bill_length_mm bill_depth_mm flipper_length_mm \


0 Adelie Torgersen 39.1 18.7 181.0

97
1 Adelie Torgersen 39.5 17.4 186.0
2 Adelie Torgersen 40.3 18.0 195.0
3 Adelie Torgersen NaN NaN NaN
4 Adelie Torgersen 36.7 19.3 193.0
.. … … … … …
339 Gentoo Biscoe NaN NaN NaN
340 Gentoo Biscoe 46.8 14.3 215.0
341 Gentoo Biscoe 50.4 15.7 222.0
342 Gentoo Biscoe 45.2 14.8 212.0
343 Gentoo Biscoe 49.9 16.1 213.0

body_mass_g sex
0 3750.0 Male
1 3800.0 Female
2 3250.0 Female
3 NaN NaN
4 3450.0 Female
.. … …
339 NaN NaN
340 4850.0 Female
341 5750.0 Male
342 5200.0 Female
343 5400.0 Male

[344 rows x 7 columns]

[67]: [Link](x='bill_length_mm',y='flipper_length_mm',data=df1)
[Link]()

98
[58]: [Link](x='bill_length_mm',y='flipper_length_mm',data=df1,hue='sex')
[Link]()

99
[ ]: #Which of the following is not a type of plot available in seaborn?
# line plot,scatter plot ,bar plot,tree plot Answer-tree plot

[68]: sns.
↪lineplot(x='bill_length_mm',y='flipper_length_mm',data=df1,hue='sex',palette='rocket_r')␣

↪#palette is used for the color change

[Link]()

100
[77]: [Link](x='bill_length_mm',y='flipper_length_mm',data=df1,hue='sex',
style='sex',markers=["o",">"])#style and markers is used at the␣
↪same time used to mark the upper and lowers limits

[Link]()

101
[78]: df1=sns.load_dataset('penguins').head(20)
df1

[78]: species island bill_length_mm bill_depth_mm flipper_length_mm \


0 Adelie Torgersen 39.1 18.7 181.0
1 Adelie Torgersen 39.5 17.4 186.0
2 Adelie Torgersen 40.3 18.0 195.0
3 Adelie Torgersen NaN NaN NaN
4 Adelie Torgersen 36.7 19.3 193.0
5 Adelie Torgersen 39.3 20.6 190.0
6 Adelie Torgersen 38.9 17.8 181.0
7 Adelie Torgersen 39.2 19.6 195.0
8 Adelie Torgersen 34.1 18.1 193.0
9 Adelie Torgersen 42.0 20.2 190.0
10 Adelie Torgersen 37.8 17.1 186.0
11 Adelie Torgersen 37.8 17.3 180.0
12 Adelie Torgersen 41.1 17.6 182.0
13 Adelie Torgersen 38.6 21.2 191.0
14 Adelie Torgersen 34.6 21.1 198.0
15 Adelie Torgersen 36.6 17.8 185.0
16 Adelie Torgersen 38.7 19.0 195.0

102
17 Adelie Torgersen 42.5 20.7 197.0
18 Adelie Torgersen 34.4 18.4 184.0
19 Adelie Torgersen 46.0 21.5 194.0

body_mass_g sex
0 3750.0 Male
1 3800.0 Female
2 3250.0 Female
3 NaN NaN
4 3450.0 Female
5 3650.0 Male
6 3625.0 Female
7 4675.0 Male
8 3475.0 NaN
9 4250.0 NaN
10 3300.0 NaN
11 3700.0 NaN
12 3200.0 Female
13 3800.0 Male
14 4400.0 Male
15 3700.0 Female
16 3450.0 Female
17 4500.0 Male
18 3325.0 Female
19 4200.0 Male

[83]: sns.
↪lineplot(x='bill_length_mm',y='flipper_length_mm',data=df1,hue='sex',style='sex',markers=['o

[83]: <Axes: xlabel='bill_length_mm', ylabel='flipper_length_mm'>

103
[87]: sns.
↪lineplot(x='bill_length_mm',y='flipper_length_mm',data=df1,hue='sex',style='sex',markers=['o

[Link]()
[Link]('This is a graph of sexs of pengunis')
[Link]()

104
[ ]: #which function is used to create a histogram in seaborn?
#[Link]()

29 Day-19 Seaborn Part-02


Bar plot in seaborn library
[88]: import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns

[90]: df=sns.load_dataset('penguins')
df

[90]: species island bill_length_mm bill_depth_mm flipper_length_mm \


0 Adelie Torgersen 39.1 18.7 181.0
1 Adelie Torgersen 39.5 17.4 186.0
2 Adelie Torgersen 40.3 18.0 195.0

105
3 Adelie Torgersen NaN NaN NaN
4 Adelie Torgersen 36.7 19.3 193.0
.. … … … … …
339 Gentoo Biscoe NaN NaN NaN
340 Gentoo Biscoe 46.8 14.3 215.0
341 Gentoo Biscoe 50.4 15.7 222.0
342 Gentoo Biscoe 45.2 14.8 212.0
343 Gentoo Biscoe 49.9 16.1 213.0

body_mass_g sex
0 3750.0 Male
1 3800.0 Female
2 3250.0 Female
3 NaN NaN
4 3450.0 Female
.. … …
339 NaN NaN
340 4850.0 Female
341 5750.0 Male
342 5200.0 Female
343 5400.0 Male

[344 rows x 7 columns]

[92]: df['island']

[92]: 0 Torgersen
1 Torgersen
2 Torgersen
3 Torgersen
4 Torgersen

339 Biscoe
340 Biscoe
341 Biscoe
342 Biscoe
343 Biscoe
Name: island, Length: 344, dtype: object

[99]: [Link](x='island',y='bill_length_mm',data=df,hue='sex')
[Link]()

106
30 order parameter
[105]: order1=['Dream','Torgersen','Biscoe']
[Link](x='island',y='bill_length_mm',data=df,hue='sex',order=order1)
[Link]()

107
31 hue_order is used to change the occurence of the bar which
we want to display
[106]: order1=['Dream','Torgersen','Biscoe']
sns.
↪barplot(x='island',y='bill_length_mm',data=df,hue='sex',order=order1,hue_order=['Female','Ma

[Link]()

108
[107]: order1=['Dream','Torgersen','Biscoe']
[Link](x='island',y='bill_length_mm',data=df,hue='sex',order=order1)
[Link]()

109
[113]: order2=['Biscoe','Dream','Torgersen']
[Link](x='island',y='bill_length_mm',data=df,hue='sex',palette='Accent')

[113]: <Axes: xlabel='island', ylabel='bill_length_mm'>

110
[114]: order1=['Dream','Torgersen','Biscoe']
sns.
↪barplot(x='island',y='bill_length_mm',data=df,hue='sex',order=order1,palette='prism')

[Link]()

111
[118]: order1=['Dream','Torgersen','Biscoe']
sns.
↪barplot(x='island',y='bill_length_mm',data=df,hue='sex',order=order1,palette='gist_heat_r')

[Link]()

112
32 Saturation
it is used to darken or lighten the graph the range must be given from 0-1
[123]: order1=['Dream','Torgersen','Biscoe']
sns.
↪barplot(x='island',y='bill_length_mm',data=df,hue='sex',order=order1,saturation=0.

↪2)

[Link]()

113
33 Histogram in seaborn
[124]: df

[124]: species island bill_length_mm bill_depth_mm flipper_length_mm \


0 Adelie Torgersen 39.1 18.7 181.0
1 Adelie Torgersen 39.5 17.4 186.0
2 Adelie Torgersen 40.3 18.0 195.0
3 Adelie Torgersen NaN NaN NaN
4 Adelie Torgersen 36.7 19.3 193.0
.. … … … … …
339 Gentoo Biscoe NaN NaN NaN
340 Gentoo Biscoe 46.8 14.3 215.0
341 Gentoo Biscoe 50.4 15.7 222.0
342 Gentoo Biscoe 45.2 14.8 212.0
343 Gentoo Biscoe 49.9 16.1 213.0

body_mass_g sex
0 3750.0 Male
1 3800.0 Female

114
2 3250.0 Female
3 NaN NaN
4 3450.0 Female
.. … …
339 NaN NaN
340 4850.0 Female
341 5750.0 Male
342 5200.0 Female
343 5400.0 Male

[344 rows x 7 columns]

[126]: import numpy as np


import pandas as pd
import [Link] as plt
import seaborn as sns

[129]: [Link](df['flipper_length_mm'])
[Link]()

C:\Users\Rehan\anaconda3\Lib\site-packages\seaborn\[Link]: UserWarning:
The figure layout has changed to tight
self._figure.tight_layout(*args, **kwargs)

115
[132]: #bins parameter
[Link](df['flipper_length_mm'],bins=[170,180,190,200,210,220,230,240])

C:\Users\Rehan\anaconda3\Lib\site-packages\seaborn\[Link]: UserWarning:
The figure layout has changed to tight
self._figure.tight_layout(*args, **kwargs)

[132]: <[Link] at 0x27141c7d450>

116
34 hsitogram as kde kenrel density
[137]: sns.
↪displot(df['flipper_length_mm'],bins=[170,180,190,200,220,230,240],kde=True,color='red')

[Link]()

C:\Users\Rehan\anaconda3\Lib\site-packages\seaborn\[Link]: UserWarning:
The figure layout has changed to tight
self._figure.tight_layout(*args, **kwargs)

117
35 Day-20 Plotly library
Plotly’s python graphing library makes interactive publication quality [Link] line plots,scatter
plots ,area charts,error bars,box plots,histograms,heatmaps,subplots,multiple-axes,polar charts and
bubble charts
[138]: #pip install plotly
#2D,3D,Animated graphs
#zoom in zoom out advance plots
#download option as png

[139]: pip install plotly

Requirement already satisfied: plotly in c:\users\rehan\anaconda3\lib\site-


packages (5.9.0)Note: you may need to restart the kernel to use updated
packages.

Requirement already satisfied: tenacity>=6.2.0 in

118
c:\users\rehan\anaconda3\lib\site-packages (from plotly) (8.2.2)

[142]: x=[1,2,3,4,5,6,7,8,9,10]
y=[7,2,4,5,3,1,2,7,8,9]

[143]: import [Link] as plt

[144]: [Link](x,y,color='r')
[Link]('line plot')
[Link]()

[145]: import seaborn as sns

[147]: [Link](x=x,y=y,color='red')
[Link]()

119
[149]: import [Link] as px

[152]: fig=[Link](x=x,y=y,title='line graph')


[Link]()

[153]: import plotly.graph_objects as go #second option for importing the plotly␣


↪library

[ ]: #which programming language can be used with plotly?


#1)python,R,matlab,javascrpit,2)python,Ruby,C++,3)Java,Scala,C,4)PHP,python ans:
↪-python,R,matlab,javascript

[154]: fig = [Link]([Link](x=x,y=y)) #[Link] for the ploting of points


[Link]()

[175]: x=[Link](10,20,6)
y=[Link](20,30,6)
print(x,y)

[15 15 12 14 16 10] [28 28 21 22 24 27]

120
[177]: fig=[Link](x=x,y=y,title='line Plot')
[Link]()

[178]: fig=[Link]([Link](x=x,y=y))
[Link]()

36 Adding Titles
[179]: x=[1,2,3,4,5,6,7,8,9,10]
y=[2,3,6,5,4,8,7,9,1,10]

[181]: fig=[Link]([Link](x=x,y=y))
fig.update_layout(title='Line Graph',xaxis_title='This is X␣
↪axis',yaxis_title='This is y Axis')

[Link]()

[ ]: #which plotly graph is best to show trends over time?


#1)line chart,2)BAR CHART,3)Scatter plot,4)heatmap, ans=Line chart

[182]: x1,y1=[1,2,3,4,5],[5,4,6,7,3]
x2,y2=[1,2,3,4,5],[4,3,6,2,1]
x3,y3=[1,2,3,4,5],[8,6,9,2,6]

[183]: fig=[Link]()

[186]: fig.add_trace([Link](x=x1,y=y1))
fig.add_trace([Link](x=x2,y=y2))
fig.add_trace([Link](x=x3,y=y3))
fig.update_layout(title="Line Plot",xaxis_title='The X␣
↪co-ordinates',yaxis_title='The Y co-ordinates')

[187]: fig=[Link]()

[191]: fig.add_trace([Link](x=x1,y=y1,name='Line1',mode='lines'))
fig.add_trace([Link](x=x2,y=y2,name='Line2',mode='markers'))
fig.add_trace([Link](x=x3,y=y3,name='Line3',mode='lines+markers'))
[Link]()

[ ]: #which of the following plotly charts type is best for comparing multiple data␣
↪series?

#[Link] charts,[Link] charts,[Link] charts,[Link],ans=bar charts

121
37 Bubble charts
[192]: import plotly.graph_objects as go

[193]: x=[12,3,4]
y=[4,6,8,10]

[198]: fig=[Link]([Link](x=x,y=y,mode='markers',marker_size=[40,60,70]))
[Link]()

[199]: fig=[Link]([Link](x=x,y=y,mode='markers',marker_size=[40,60,70], #text␣


↪parameter add an text to the bubbles we can name which brand bubble it is␣

↪and what does it contains

text=['product A','product B','product C']))


[Link]()

[ ]:

[ ]:

[ ]:

122

You might also like