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

Python Environment Setup Guide

The document outlines a practical guide for setting up the Python environment using Anaconda, including installation steps and an introduction to various Python IDEs such as IDLE, Jupyter Notebook, PyCharm, and Spyder. It also includes practical exercises for creating and manipulating lists and dictionaries in Python, demonstrating operations like appending, removing duplicates, and updating details. The document serves as a foundational resource for students in the Computer Engineering department at MadhubenandBhanubhai Patel Institute of Technology.

Uploaded by

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

Python Environment Setup Guide

The document outlines a practical guide for setting up the Python environment using Anaconda, including installation steps and an introduction to various Python IDEs such as IDLE, Jupyter Notebook, PyCharm, and Spyder. It also includes practical exercises for creating and manipulating lists and dictionaries in Python, demonstrating operations like appending, removing duplicates, and updating details. The document serves as a foundational resource for students in the Computer Engineering department at MadhubenandBhanubhai Patel Institute of Technology.

Uploaded by

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

MADHUBENANDBHANUBHAIPATEL INSTITUTE

OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-1
AIM: Understanding Python environment Setup: Installing python with
anaconda,Introduction to various Python IDEs like IDLE, Jupyter notebook,
Pycharm,Spyder.

InstallingPythonwithAnaconda:
• Anaconda is an open-source software that contains Jupyter, spyder, etc that are used forlarge data
processing, data analytics, heavy scientific computing. Anaconda works for Rand python
programming language. Spyder(sub-application of Anaconda) is used forpython.

Anaconda comes with over 1,500 packages (including the package management system Conda)and
a GUInamed [Link] AnacondaNavigatoralso installs someapplications by default
such as Jupyter Notebook, Spyder IDE, and RStudio (for R).

Step-1:[Link]
[Link],anddownloadtheAnacondaversionforWindows.

Step-2:Download thelatest Python3version forWindows

ENROLLNO:-12302040701118 PAGE|1
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

Step 3:Double-clickontheexecutablefile

Step-4:ClickNext

Step-5:SelectWhoYouWantToGiveAnacondaTo

ENROLLNO:-12302040701118 PAGE|2
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

Step-6:Selecttheinstallationlocation

Step-7:ClickNextandthen“Finish”

Step-8:Selecttheenvironmentvariables

IfYouAreInstallingPythonForTheFirstTime

ENROLLNO:-12302040701118 PAGE|3
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

IfYouAlreadyHave PythonInstalled

Step-9:SeeifPython IsInstalled

Andafteropeningit,youwillbeabletoseethevariouspackages&libraries.

ENROLLNO:-12302040701118 PAGE|4
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

IntroductiontovariousPythonIDEs:

IntegratedDevelopmentEnvironment(IDE):
IDEs are full-fledged environments, which provide all the essential tools needed for software
development. Theydon’t just handle the code (forexample, write, edit, syntax highlighting, and auto-
completion) butalso provideother featuressuchasdebugging, execution, testing, and codeformatting
that help programmers.

1. IDLE:

It is a cross-platformopen-source IDE that comes bydefault with Python, so you don’t need to worry
about the installationor setup. IDLE is written in Pythonand is suitable for beginner-leveldevelopers
who want to practice Python development. IDLE is lightweight and simple to use, so you can build
simple projects such as web browser game automation, basic web scraping applications, and office
automation. This IDE is not good for larger projects, so move to some advanced IDEs after learning
the basics from IDLE.
• Pythonshellwithsyntaxhighlighting
• Callstack’sclear visibility
• Amulti-windowcodeeditorthatallowsfeatureslikesmartindentation, autocomplete, etc.
• Ithasaninteractiveinterpreterwithcolorizingofinput,output,and errormessages.
• Programanimationor stepping.

2. JupyterNotebook:

Jupyter Notebook is a web-based interactive development environment; it’s well known in thedata
science community for analyzing, sharing, and presenting information. It is easy-to-use, open-
source software that allows you to create and share live code, visualizations, etc. Some of its good
features are given below.

 Supportfornumericalsimulation,datacleaning,machinelearning,datavisualization,andstatistical
modeling.
 Markdownand HTMLintegration.
 Integrateddatasciencelibraries(matplotlib,NumPy,Pandas).
 YoucanalsoconvertyourcompleteworkintoPDFandHTMLfiles,or youcanjustexportitasa
.pyfile.
 Startingandstoppingservers, openingfoldersandfiles.

ENROLLNO:-12302040701118 PAGE|5
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

HomepageofJupyterNotebook:

CommandpromptforJupyter Navigator:

ENROLLNO:-12302040701118 PAGE|6
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

CreateNewPythonFile(ipynbfile):

TypesofCellsinJupyterNotebook:

MarkdownCell:
Herewecanwriterelativedetailsor documentationinaJupyterfile.

ENROLLNO:-12302040701118 PAGE|7
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

RunningaPythoncodeinJupyterNotebook:

3. PyCharm:

In industries, most professional developers use PyCharm, and it has been considered the best IDE
for Python developers. It was developed by the Czech company JetBrains and is a cross-platform
IDE. It gives dailytips to improve your knowledge ofhow you canuse itmore efficiently, which is a
very good feature. It comes in two versions: a community version and a professional version, where
the community version is free but the professional version is paid. Below are some other features of
this IDE:

 Itisconsideredanintelligentcodeeditor,fastandsaferefactoring, andsmartcode.
 Featuresfordebugging,profiling,remotedevelopment,testingthecode,autocodecompletion, quick
fixing, error detection, and tools for the database.
 Supportforpopularwebtechnologies,webframeworks,scientificlibraries,andversioncontrol.

ENROLLNO:-12302040701118 PAGE|8
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

4. Spyder:

Spyderis another goodopen-source and cross-platformIDE written in Python. It is also called the
Scientific Python Development IDE and is the most lightweight IDE for Python. It is mainly used
by data scientists who can integrate with Matplotlib, SciPy, NumPy, Pandas, Cython, IPython,
SymPy, and other open-source software. It comes with the Anaconda package manager distribution
and has some good advanced features such as edit, debug, and data exploration. Below are some
other features of this IDE:

• Autocodecompletionandsyntaxhighlighting.
• Abilitytosearchandedit thevariablesfromthegraphicaluserinterfaceitself.
• Static codeanalysis.

ENROLLNO:-12302040701118 PAGE|9
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|10
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
PRACTICAL-2
Prac-2.1:
 Create a list named “Subjects” by inserting 10 subjects into it through any loop and create a list
“ElectiveSubjects”with5subjectsthroughdirect [Link] list “Subject”byanotherlist
“Elective Subjects”. Append 3 duplicate subjects into “Subject” list. Find the index of first
occurrence of that duplicate value and then remove all the occurrences of that specific subject
through loop.
 Define function remove range(i1,i2) to remove range of element from i1 to i2 through del keyword
and return the resultant list. Pop 5th element after reversing and sorting your list. Count total
elements in your list and finally clear the list. Which of the above operations can be performed
directly? Which of the above operations cannot be performed directly on Tuple and why? Update
and remove specific item from the tuple by converting it into list.

In[1]:
Subjects= []
for i in range(1, 11):
[Link]("Subject"
+str(i))
print("SubjectsList:",Subjects)

Elective_Subjects=["AI","ML","IOT","Robotics","Cybersecurity"]
print("Elective Subjects:", Elective_Subjects)

[Link](Elective_Subjects)
print("AfterExtending:",Subjects)

[Link]("AI")
[Link]("AI")
[Link]("AI")
print("AfterAppendingDuplicates:",Subjects)

dup_subject="AI"
first_index=[Link](dup_subject)
print(f"Firstoccurrenceof'{dup_subject}':", first_index)

while dup_subject in Subjects:


[Link](dup_subject)
print("AfterRemovingAllDuplicates:",Subjects)

defremove_range(i1,i2):
del Subjects[i1:i2]
return Subjects

Subjects=remove_range(2,5)
print("AfterRemovingRange(2to5):",Subjects)

ENROLLNO:-12302040701118 PAGE|11
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

In[2]:
[Link]()
[Link]()

iflen(Subjects)>4:
popped = [Link](4)
print("Popped5thElement:",popped)
else:
print("Listdoesn'thave5elements.")
print("List After Pop:", Subjects)
print("Total Elements:", len(Subjects))

[Link]()
print("Listafterclear:",Subjects)
print()

print("\nTupleOperations:")
print("✔️Accessingelements, usingcount() andindex() canbedonedirectly.")print("❌Adding, removing,
or updating cannot be done directly because tuples are immutable.")

my_tuple=("Maths","Science","History","English")
temp_list = list(my_tuple)

temp_list[2]="Geography"temp_list.rem
o ve("Science")

my_tuple = tuple(temp_list)
print("UpdatedTuple:",
my_tuple)

ENROLLNO:-12302040701118 PAGE|12
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
OUTPUT:

Prac-2.2:
 Create a dictionary named “Students Data” with 5 students and id_no, name and marks as the key
values. Provide the separate list of all the keys and values. Add details of one more [Link]
value corresponding to specific keythroughget [Link] a functionupdate detail(k) by looping
over keys to search for specific key ‘k’ whose details to be updated and then update it with
newdetails and return updated dictionary. If specific detail is not available in list print
appropriatemessage.
 Convert dictionary’s keys into a list by looping through keys and appending it to the other list.
Convert dictionary values into list through list constructor. Count and display total number of
students in the dictionary. Remove all the details from the dictionary. Define a dictionary named
“exam_data_array” with 4 keys, namely ‘name’, ‘score’, ‘attempts’ and ‘qualify’. Values for eachof
these 4 keys will be an 1Darray with 5 elements. by creating a dictionary named“exam_data_list”
with 5 list and each list stores all 4 key-value pairs for single student.
In[3]:
Students_Data={ 101:
{"name":"Amit","marks":87},
102:{"name":"Riya","marks":91},
103:{"name":"Jay","marks":76},
104:{"name":"Kiran","marks":89},
105:{"name":"Neha","marks":93}
}
print("\nStudents Data:", Students_Data)
print("\nKeys:", list(Students_Data.keys()))
print("Values:",
list(Students_Data.values()))

Students_Data[106]={"name":"Vikas", "marks":84}

print("\nAfter Adding 1 Student:", Students_Data) print("\


nDetailsofID103:",Students_Data.get(103))

defupdate_detail(k):
ifkinStudents_Data
:
name = input("Enter new name: ")
marks=int(input("Enternewmarks:"))
Students_Data[k]={"name":name,"marks":marks}returnStudents_Data

else: print("Student IDnotfound.")

ENROLLNO:-12302040701151 PAGE|13
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

In[4]:
keys_list=[]
forkeyinStudents_Data.keys():
keys_list.append(key) print("\
nKeysasList:",keys_list)

values_list = list(Students_Data.values())
print("Values as List:", values_list) print("\
nTotal Students:", len(Students_Data))
Students_Data.clear()
print("AfterClearing:",Students_Data)

exam_data_array={ "name":
["Amit","Riya","Jay","Kiran","Neha"], "score": [88,
92, 76, 85, 90],
"attempts":[1,1,2,1,2], "qualify":
["yes","yes","no","yes","yes"]
}print("\nExamDataArray:",exam_data_array)

exam_data_list=[
{"name":"Amit","score":88,"attempts":1,"qualify":"yes"},
{"name":"Riya","score":92,"attempts":1,"qualify":"yes"},
{"name":"Jay","score":76,"attempts":2,"qualify":"no"},
{"name":"Kiran","score":85,"attempts":1,"qualify":"yes"},
{"name":"Neha","score":90,"attempts":2,"qualify":"yes"}]
print("\nExam Data List:", exam_data_list)

ENROLLNO:-12302040701118 PAGE|14
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

ENROLLNO:-12302040701118 PAGE|15
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-3
Prac-3.1:
Do the slicing of a given String to generate various substring by passing different index (like positive
index, negative index, end index> string length, entire string), split this string into chunks oflength 3
using list comprehension, split the string with specific character, iterate over the words of string.
Applytrim, toupper, tolower, replace string and character, title, join and other operations on String.

In[1]:

print("===STRINGOPERATIONS===")
sample="HelloPythonWorld"

print("\n--- String Slicing ---")


print("Original String:", sample)
print("Positiveindex[0:5]:",sample[0:5])
print("Negativeindex[-5:]:",sample[-5:])
print("Endindex>length[0:50]:",sample[0:50])
print("Entire string [:]:", sample[:])

print("\n---ChunkofLength3---")
chunks=[sample[i:i+3]foriinrange(0,len(sample),3)]
print("Chunks:", chunks)

print("\n---SplitwithSpecificCharacter---")
split_string = "Hello-World-Python"
print("Split on '-':", split_string.split('-'))

print("\n---IterateoverWords---")
sentence = "Python is powerful"
for word in [Link]():
print("Word:", word)

print("\n---StringMethods---")
str1 = "Welcome to Python"

print("Original:", repr(str1))
print("Trim:",
repr([Link]()))
print("Upper:", [Link]())
print("Lower:",[Link]())

print("Replace'Python'with'Programming':",[Link]("Python","Programming"))
print("Title Case:", [Link]())
print("Joinwith'-':","-".join(["Join","These", "Words"]))

ENROLLNO:-12302040701118 PAGE|16
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

Performadd,union,intersection,difference,symmetric_difference,union,intersection_update,
symmetric_difference_update, difference_update, discard, issubset,
issuperset,isdisjoint, remove,popandclearoperationsonSet.
In[2]:
print("\n===SETOPERATIONS===")
set1 = {1, 2, 3, 4, 5}
set2= {4,5,6,7,8}
print("Set1:",set1)
print("Set2:",set2)
[Link](6)
print("After add(6):", set1)
print("Union:",
[Link](set2))
print("Intersection:", [Link](set2))
print("Difference(set1-set2):",[Link](set2))
ENROLLNO:-12302040701118 PAGE|17
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
p ence(set2))
r
i
n
t
(
"
S
y
m
m
e
t
r
i
c
D
i
f
f
e
r
e
n
c
e
:
"
,
s
e
t
1
.
s
y
m
m
e
t
r
i
c
_
d
i
f
f
e
r
ENROLLNO:-12302040701118 PAGE|18
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

set1_temp = [Link]()
set1_temp.intersection_update(set2)
print("Afterintersection_update:",set1_temp)
set1_temp = [Link]()
set1_temp.symmetric_difference_update(set2)
print("After symmetric_difference_update:",
set1_temp) set1_temp = [Link]()
set1_temp.difference_update(set2)
print("After difference_update:", set1_temp)
[Link](3)
print("After discard(3):", set1)
[Link](2)
print("After remove(2):", set1)
popped = [Link]()
print("After pop():",set1,"|Popped:",popped)
print("Is subset:", {4, 5}.issubset(set2))
print("Issuperset:",[Link]({4,5}))
print("Isdisjoint(set1&set2):",[Link](set2))
[Link]()
print("Afterclear():",set1)

OUTPUT:

ENROLLNO:-12302040701118 PAGE|19
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

Prac-3.2:
Importarraymoduleinpythonand performalloperationsavailableinthe module.
In[3]: print("\
n===ARRAYOPERATIONS===")
importarray
arr=[Link]('i',[1,2,3,4,5])
print("Original Array:", arr)
[Link](6)
print("Afterappend(6):",arr)
[Link](2, 10)
print("Afterinsert(2,10):",arr)
[Link]()
print("Afterpop():",arr)
[Link](3)
print("After remove(3):", arr)
print("Indexof10:",[Link](10))
[Link]()
print("After reverse():", arr)
print("Buffer info:", arr.buffer_info())
print("Count of 2:", [Link](2))
[Link]([7, 8, 9])
print("After extend([7,8,9]):", arr)
print("Array to list:", [Link]())

OUTPUT:

ENROLLNO:-12302040701118 PAGE|20
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-4
Prac-4:
Download “heart_2020_cleaned.csv” datasetfrom
“[Link] “ and
performallthedescriptivestatisticsonabovedataset using statistics [Link]
package(Measuresofcentraltendency, measureofdispersion/variation, measureoflocation, measure of
shape and symmetry).
In[1]:
importpandasaspd import
statistics
[Link]
import numpy as np

heart_data = pd.read_csv('C:/Users/student/Downloads/heart_2020_cleaned.csv')

print("Dataset Info:")
print(heart_data.info())

numerical_columns = heart_data.select_dtypes(include='number').columns
descriptive_stats = {}

for col in numerical_columns:


data
=heart_data[col].dropna()
mode_result = [Link](data, nan_policy='omit')
mode_array = np.atleast_1d(mode_result.mode)
mode_count = np.atleast_1d(mode_result.count)
mode_value=mode_array[0]ifmode_count[0] >0elseNone

descriptive_stats[col] = {
'mean':[Link](data),
'median':[Link](data),
'mode': mode_value,
'variance':[Link](data),
'stdev': [Link](data),
'min': min(data),
'max':max(data),
'range':max(data)-min(data),
'skewness': [Link](data),
'kurtosis':
[Link](data)
}

forcol,stats_dictindescriptive_stats.items():
print(f"\nDescriptiveStatistics for{col}:")

ENROLLNO:-12302040701118 PAGE|21
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
for stat, value in stats_dict.items():
print(f"{stat}:{value}")

ENROLLNO:-12302040701118 PAGE|22
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

ENROLLNO:-12302040701118 PAGE|23
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-5
Prac-5.1:
WritefollowingprogramonPandas DataFrame:
 Createan array “rank” with 5 element(rank1,rank2,…,rank5). Create and display a DataFrame
“exam”fromaspecifieddictionary“exam_data_array”with“rank”aslabel. Also displayasummary
of basic information and its data. Perform following operations on DataFrame “exam” :
 Selecttherowswherethescoreisbetween15 and20 (inclusive).
 Sortthedatafirstby“score” inascendingorder,thenby“name”indescendingorder.
 Replacethe'yes'and'no'valuesfromcolumn “qualify”withTrueandFalse.
 Displayspecifiedcolumns(columns:2and4)androws(row:1,3and 5).
 Selecttherowswherenumberofattemptsintheexaminationis lessthan2andscoregreaterthan 15.
 Changethename'James'to'Suresh'in “name”columnofthedata frame.
 Calculatethe sumoftheexaminationattemptsbythestudents
 Appendonerow.
 Insertanewcolumn“exam_name”andthenDeletethe”exam_name”column.
 ConvertaNumPyarray,dictionaryandfirstcolumnofaDataFrametoaseries.

In[1]:

importpandasaspd
importnumpyasnp
rank=['rank1','rank2','rank3','rank4','rank5'] exam_data_array
={
'name':['Annie','James','Catherine','Michael','Laura'],
'score': [18, 20, 16, 19, 17],
'attempts':[1,3,2,1,1], 'qualify':
['yes','no','yes','no','yes']
}
exam= [Link](exam_data_array, index=rank)
print("DataFrame 'exam':\n", exam)
print("\nBasic Information Summary:")
print([Link]())
print("\nData Summary:")
print([Link](include='all'))

filtered_exam = exam[(exam['score'] >= 15) & (exam['score'] <= 20)] print("\


nRows where the score is between 15 and 20:\n", filtered_exam)
sorted_exam=exam.sort_values(by=['score','name'],ascending=[True,False])
print("\nDatasortedby'score'(ascending)and'name'(descending):\n",sorted_exam) exam['qualify'] =
exam['qualify'].map({'yes': True, 'no': False}) print("\
nDataFrameafterreplacing'yes'/'no'in'qualify'withTrue/False:\n",exam)
selected_data = [Link][[0, 2, 4], [1, 3]] print("\
nSpecifiedcolumns(2and4)androws(1,3,and5):\n",selected_data)
filtered_attempts = exam[(exam['attempts'] < 2) & (exam['score'] > 15)]
print("\nRows where attempts < 2 and score > 15:\n", filtered_attempts)
[Link][exam['name'] == 'James', 'name'] = 'Suresh' print("\
nDataFrameafterchanging'James'to 'Suresh':\n", exam)

ENROLLNO:-12302040701118 PAGE|24
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

total_attempts = exam['attempts'].sum() print("\


nSumofexaminationattemptsbythestudents:", total_attempts)
new_row=[Link]({'name':['Kevin'],'score':[15],'attempts':[1],'qualify':[True]},index=['rank6'])
exam= [Link](new_row)
print("\nDataFrameafterappendingonerow:\n",exam)
exam['exam_name'] = 'Final Exam' print("\
nDataFrameafterinserting'exam_name'column:\n",exam)
[Link]('exam_name', axis=1, inplace=True) print("\
nDataFrameafterdeleting 'exam_name'column:\n",exam)

numpy_array = [Link]([1, 2, 3, 4, 5])


numpy_series=[Link](numpy_array) print("\
nNumPyarrayconvertedtoSeries:\n",numpy_series)
dictionary = {'a': 10, 'b': 20, 'c': 30}
dictionary_series=[Link](dictionary) print("\
nDictionaryconvertedtoSeries:\n",dictionary_series)
name_series = exam['name']
print("\nFirstcolumn('name')ofDataFrameconvertedtoSeries:\n", name_series)

OUTPUT:

ENROLLNO:-12302040701118 PAGE|25
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|26
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRAC-5.2

WritefollowingprogramonNumPyArray:
 Createanarrayofallthe evenintegersfrom30to70.
 Createanarrayof10 zeros,otherwith10ones,andonemorewith10fives.
 Createavectoroflength10 withvaluesevenlydistributed between5 and50.
 Createa3x4 matrix filled withvalues from10 to 21 and computesumofallelements,
sumofeach column and sum of each row of a given array.
 Createa3x4arrayandfindthemissingdatainthearray.
 Calculate round, floor, ceiling, truncated and round (to the given number of decimals) of the input,
element-wise of an array.
 Find the maximum and minimum value, median , Weighted average, mean, standard deviation,
variance, covariance matrix, of a given flattened array, minimum and maximum value along the
second axis. Create a structured array from given student name, height, class and their data types.
Now sort by class, then height if class are equal.

In[1]:

importnumpyasnp

even_integers=[Link](30,71,2)
print("Arrayofevenintegersfrom30to70:\n", even_integers)

zeros_array=[Link](10)
ones_array = [Link](10)
fives_array=[Link](10,5)
print("\nArrayof10zeros:\n",zeros_array) print("\
nArray of 10 ones:\n", ones_array) print("\
nArrayof10 fives:\n", fives_array)

evenly_distributed=[Link](5,50,10) print("\
nVectoroflength10withvaluesevenlydistributedbetween5and50:\n",
evenly_distributed)

matrix_3x4 = [Link](10, 22).reshape(3, 4)


sum_all_elements = [Link](matrix_3x4)
sum_each_column=[Link](matrix_3x4,axis=0)
sum_each_row = [Link](matrix_3x4, axis=1)
print("\n3x4Matrixfilledwithvaluesfrom10to21:\n",matrix_3x4)
print("\nSum of all elements in the matrix:", sum_all_elements)
print("\nSum of each column:", sum_each_column) print("\
nSumofeachrow:", sum_each_row)

ENROLLNO:-12302040701118 PAGE|27
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

array_with_nan=[Link]([[1,2,[Link],4],[5,[Link],7,8],[9,10,11,[Link]]]) missing_data
= [Link](array_with_nan)
print("\n3x4 Array with missing data:\n", array_with_nan) print("\
nMissingdatainthearray(TruerepresentsNaN):\n", missing_data)

input_array=[Link]([1.55,2.75,-3.14,4.99,-5.87])
rounded_array = [Link](input_array)
floor_array = [Link](input_array)
ceiling_array = [Link](input_array)
truncated_array = [Link](input_array)
rounded_to_decimals=[Link](input_array,1)

print("\nOriginal Array:\n", input_array) print("\


nRounded Array:\n", rounded_array) print("\
nFloor Array:\n", floor_array) print("\nCeiling
Array:\n", ceiling_array) print("\nTruncated
Array:\n", truncated_array)
print("\nRoundedArrayto1decimalplace:\n",rounded_to_decimals)

flattened_array = matrix_3x4.flatten()
max_value = [Link](flattened_array)
min_value = [Link](flattened_array)
median_value = [Link](flattened_array)
weighted_avg=[Link](flattened_array,weights=[Link](1, len(flattened_array)
+1))
mean_value = [Link](flattened_array)
std_deviation = [Link](flattened_array)
variance_value = [Link](flattened_array)
covariance_matrix = [Link](flattened_array)
min_second_axis = [Link](matrix_3x4, axis=1)
max_second_axis=[Link](matrix_3x4,axis=1)

print("\nFlattened Array:\n", flattened_array)


print("\nMaximum value:", max_value) print("\
nMinimum value:", min_value) print("\nMedian
value:", median_value) print("\nWeighted
average:", weighted_avg) print("\nMean value:",
mean_value) print("\nStandard Deviation:",
std_deviation) print("\nVariance:",
variance_value)

ENROLLNO:-12302040701118 PAGE|28
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

print("\nCovariance matrix:\n", covariance_matrix) print("\


nMinimum value alongthe second axis:", min_second_axis) print("\
nMaximumvaluealongthesecondaxis:",max_second_axis)
student_data=[Link]([('John',5.9,10),('Alice',5.5,12),('Bob',6.1,10),('Mary',5.7,
11)],
dtype=[('name', 'U10'), ('height', 'f4'), ('class', 'i4')])
sorted_students=[Link](student_data,order=['class','height']) print("\
nStructuredArraysortedby'class'andthen'height':\n",sorted_students)

OUTPUT:

ENROLLNO:-12302040701118 PAGE|29
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-6

Prac-6:
WritefollowingpythonprogramsonBeautifulSoup PerformfollowingoperationsonaHTML document.
● Findthetitle tagfroma givenhtmldocument.
● Countandretrievealltheparagraphtagsandextractthetextinthefirstparagraphtag.
● Findthetext ofthefirst tagandlengthofthetextofthefirsttag.
● Findthehrefofthefirsttag.
● Findthefirst tagwithagivenattributevalueinanhtmldocument.

.In[1]:

frombs4importBeautifulSoup
html_doc = """
<!DOCTYPEhtml>
<html>
<head>
<title>SampleHTMLDocument</title>
</head>
<body>
<h1>MainHeading</h1>
<p>Thisisthefirstparagraph.</p>
<p>This isthesecond paragraph.</p>
<ahref="[Link]
<h2>SubHeading</h2>
</body>
</html>"""
soup=BeautifulSoup(html_doc,'[Link]')title_tag=[Link]
print("Title tag:", title_tag)

paragraph_tags=soup.find_all('p')
print("\nNumber of paragraph tags:", len(paragraph_tags))
print("Textofthefirstparagraphtag:",paragraph_tags[0].get_text())

first_a_tag_text = [Link]('a').get_text()
first_h2_tag_text = [Link]('h2').get_text() print("\
nTextofthefirst<a>tag:",first_a_tag_text)
print("Lengthofthetextofthefirst<h2>tag:",len(first_h2_tag_text))

first_a_tag_href=[Link]('a')['href'] print("\
nHrefofthefirst<a>tag:",first_a_tag_href)

first_tag_with_attribute = [Link](attrs={"href": "[Link] print("\


nFirsttagwithhref='[Link]

ENROLLNO:-12302040701118 PAGE|30
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

PRAC-6.2

Write a python program for MySQL Database connectivity(import sqlite3 module) Establish the
connection with Education database named “Education” in SQLite , create a table named
Student(with id_no, name, department, gander, total_marks) in Education database. Perform insert,
update,select and delete operation on Student table.

import sqlite3

conn=
[Link]('[Link]')
cursor = [Link]()

[Link]('''
CREATETABLEIFNOTEXISTSStudent( id_no
INTEGER PRIMARY KEY,
nameTEXTNOTNULL,
department TEXT,
gender TEXT,
total_marksINTEGER
)
''')
students_to_insert=[
(1,'JohnDoe', 'ComputerScience', 'Male', 85),
(2,'JaneDoe','ElectricalEngineering','Female',90), (3,
'Alice', 'MechanicalEngineering', 'Female', 75)]
[Link]( "INSERTORIGNOREINTOStudent(id_no,name,department,gender,total_marks)
VALUES (?, ?,
?, ?, ?)",
students_to_insert
)
[Link]()

ENROLLNO:-12302040701118 PAGE|31
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

[Link]("SELECT*FROMStudent")
print("Students table after insertion:")
forstudent [Link]():
print(student)
[Link]("UPDATEStudentSETtotal_marks=95WHEREid_no=2")
[Link]()

[Link]("SELECT*FROMStudent")
print("\nStudents table after update:")
forstudent [Link]():
print(student)

[Link]("DELETEFROMStudentWHEREid_no=3")
[Link]()

[Link]("SELECT*FROMStudent")
print("\nStudents table after deletion:")
forstudent [Link]():
print(student)
[Link]()

OUTPUT:

ENROLLNO:-12302040701118 PAGE|32
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-7
Prac-7:
Writeapythonprogramto download appropriatedatasetandexplorerandomvariable,Probability
massfunction,Probabilitydensityfunction,Cumulativedistributionfunction,Discreteprobability
distribution and continuous probability distribution using [Link] , rv_discrete class and
rv_continuous class .

In[1]:

importnumpyasnp
importpandasaspd
[Link]
import seaborn as sns
fromscipyimportstats

data=sns.load_dataset('tips')

print("Firstfewrowsofthetipsdataset:")
print([Link]())

total_bill=data['total_bill']
size = data['size']

values,counts=[Link](size,return_counts=True)
pmf = counts / len(size)

rv_discrete=stats.rv_discrete(name='size',values=(values,pmf))

[Link](values, pmf, alpha=0.7)


[Link]('ProbabilityMassFunction(PMF)for"size"')
[Link]('Size')
[Link]('Probability')
[Link]()

mu, std = [Link](total_bill)

rv_continuous=[Link](loc=mu,scale=std)

x=[Link](min(total_bill),max(total_bill),100)
pdf = rv_continuous.pdf(x)

[Link](x,pdf,label=f'NormalPDF\n$\mu={mu:.2f},\sigma={std:.2f}$')

ENROLLNO:-12302040701118 PAGE|33
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

[Link](total_bill,density=True,bins=20,alpha=0.5,color='g',label='Histogram
of total_bill')

[Link]('ProbabilityDensityFunction(PDF)for"total_bill"')
[Link]('Total Bill')
[Link]('Density')
[Link]()
[Link]()

cdf = rv_continuous.cdf(x)

[Link](x,cdf,label='CDF')
[Link]('CumulativeDistributionFunction(CDF)for"total_bill"')
[Link]('TotalBill')

[Link]('Cumulative Probability')
[Link]()
[Link]()

mean_bill = [Link](total_bill)
median_bill=[Link](total_bill)
std_bill = [Link](total_bill)
var_bill=[Link](total_bill)

print(f"Mean of total_bill: {mean_bill:.2f}")


print(f"Median of total_bill: {median_bill:.2f}")
print(f"StandardDeviationoftotal_bill:{std_bill:.2f}")
print(f"Variance of total_bill: {var_bill:.2f}")

[Link](total_bill,kde=True,stat="density",label='KDEofactualdata') [Link](x,
pdf, label='Theoretical Normal PDF', color='red')

[Link]('ComparisonofActualData vsTheoreticalNormalDistribution') [Link]('Total


Bill')

[Link]('Density')
[Link]()
[Link]()

ENROLLNO:-12302040701118 PAGE|34
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:

Firstfewrowsofthetipsdataset:
Total_Bill Tip Sex Smoker Day Time Size
16.99 1.01 Female No Sun Dinner 2
10.34 1.66 Male No Sun Dinner 3
21.01 3.50 Male No Sun Dinner 3
23.68 3.31 Male No Sun Dinner 2
24.59 3.61 Female No Sun Dinner 4

ENROLLNO:-12302040701118 PAGE|35
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

CALCULATION:

Mean of total_bill: 19.79


Medianoftotal_bill:17.80
StandardDeviationoftotal_bill:8.88
Variance of total_bill: 78.93

ENROLLNO:-12302040701118 PAGE|36
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-8
Prac-8:
Writeapythonprogramtocomputeandexplorenormaldistribution,centrallimittheorem,pointestimate, interval
estimation and hypothesis testing.

In[1]:

importnumpyasnp
[Link]
import seaborn as sns
fromscipyimportstats

mu,sigma=0,1
data=[Link](mu,sigma,1000)

[Link](data,kde=True,stat="density")
x=[Link](mu-4*sigma,mu+4*sigma,100)
pdf
= [Link](x, mu, sigma) [Link](x,pdf,label=f'NormalPDF\n$\mu={mu},\
sigma={sigma}$',color='red') [Link]('Normal Distribution')
[Link]('Value')
[Link]('Density')
[Link]()
[Link]()
uniform_data=[Link](0,1,1000)

means= []
sample_sizes=[5,10,30,50,100] for
size in sample_sizes:
sample_means=[[Link]([Link](uniform_data,size=size))for_inrange(1000)]
[Link](sample_means)

for i, size in enumerate(sample_sizes):


[Link](means[i], kde=True, stat="density")
[Link](f'CentralLimitTheorem-SampleSize{size}')
[Link]('Sample Mean')
[Link]('Density')
[Link]()

sample=[Link](mu,sigma,50)
sample_mean = [Link](sample)
print(f"PointEstimate(SampleMean):{sample_mean:.2f}")

ENROLLNO:-12302040701118 PAGE|37
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

confidence_level=0.95 ci=[Link](confidence_level,loc=sample_mean,scale=sigma/
[Link](len(sample))) print(f"95% Confidence Interval for the Mean: {ci}")
t_statistic,p_value=stats.ttest_1samp(sample,popmean=0)
print(f"t-statistic: {t_statistic:.2f}, p-value: {p_value:.4f}")

alpha=0.05
ifp_value<alpha:
print("Rejectthenullhypothesis:Thesamplemeanissignificantlydifferentfrom0.") else:
print("Failtorejectthenullhypothesis:Thesamplemeanisnotsignificantlydifferentfrom0.")

ENROLLNO:-12302040701118 PAGE|38
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
OUTPUT:

CONCLUSION:
PointEstimate(SampleMean):-0.28 95%ConfidenceIntervalfortheMean:
[np.float64(-0.5532961634319937),
np.float64(0.0010653663078774023) ]
t-statistic:-2.59,
p-value:0.0125
Rejectthenullhypothesis:Thesamplemeanissignificantlydifferentfrom0.

ENROLLNO:-12302040701118 PAGE|39
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-9
Prac-9:
 Identify the column(s) of a given DataFrame which have at least one missing value, count the
number of missing values in each column and drop the raws and columns with missing values.
Check for the null values. Also remove the duplicate values fromthe DataFrame. Handle outliers
in the Data Frame.

 Access subset of data through indexing(Select data using labels(column headings)),


Slicing(Extract range based subset, subset ofrows, subset ofcolumns, select a subset ofrows and
columns from our DataFrame using iloc method).

 Performotherdataprocessingona givendataset.

In[1]:

importpandasaspd
importnumpyasnp

data={
'A':[1,2,[Link],4, 5,5, 7,8],
'B': [10,[Link],[Link],40, 50,50,70,80],
'C':[100,200,300, 400, 500,500, 700,800],
'D':[1000,2000,3000,[Link], [Link],5000, 6000, 7000]
}

df=[Link](data)

print("OriginalDataFrame:")
print(df)

columns_with_nan = [Link][[Link]().any()].tolist() print("\


nColumns with at least one missing value:")
print(columns_with_nan)

missing_values_count = [Link]().sum() print("\


nCountofmissingvaluesineachcolumn:")
print(missing_values_count)

df_dropped = [Link](axis=0)
df_dropped_columns = [Link](axis=1)

print("\nDataFrameafterdroppingrowswithmissingvalues:")
print(df_dropped) print("\
nDataFrameafterdroppingcolumnswithmissingvalues:")
print(df_dropped_columns)

print("\nCheckfornullvaluesinthe DataFrame:")

ENROLLNO:-12302040701118 PAGE|40
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

print([Link]())

df_no_duplicates = df.drop_duplicates() print("\


nDataFrameafterremovingduplicatevalues:")
print(df_no_duplicates)

defcap_outliers(series):
Q1=[Link](0.25)
Q3=[Link](0.75)
IQR =Q3-Q1
lower_bound = Q1 - 1.5 *IQR
upper_bound=Q3+1.5*IQR
[Link](series<lower_bound,lower_bound,[Link](series>upper_bound,upper_bound, series))

df_capped= [Link](cap_outliers)

print("\nDataFrame after capping outliers:")


print(df_capped)

subset_columns=df[['A','B']] print("\
nSubsetofDataFramewithcolumnsAandB:")
print(subset_columns)

subset_rows= df[2:5] print("\


nSubsetofDataFramewithrows2to4:") print(subset_rows)

subset_iloc=[Link][2:5, [0,2]] print("\


nSubsetofDataFramewithrows2to4andcolumns0and2:")
print(subset_iloc)

mean_values = [Link]() print("\


nMeanofeachcolumn:")
print(mean_values)

df_normalized=([Link]())/([Link]()-[Link]())
print("\nNormalized DataFrame:")
print(df_normalized)

ENROLLNO:-12302040701118 PAGE|41
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

OUTPUT:
OriginalDataFrame

A B C D
1.0 10.0 100 1000.0
2.0 None 200 2000.0
None None 300 3000.0
4.0 40.0 400 None
5.0 50.0 500 None
5.0 50.0 500 5000.0
7.0 70.0 700 6000.0
8.0 80.0 800 7000.0

Columnswith atleast onemissingvalue

Columns
A
B
D

Countofmissingvaluesin eachcolumn

Column MissingCount
A 1
B 2
C 0
D 2

DataFrameafterdroppingrowswithmissingvalues

A B C D
1.0 10.0 100 1000.0
5.0 50.0 500 5000.0
7.0 70.0 700 6000.0
8.0 80.0 800 7000.0

DataFrameafterdroppingcolumnswithmissingvalues

C
100
200
300
400
500
500
700
800

ENROLLNO:-12302040701118 PAGE|42
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

Checkfornullvalues intheDataFrame

A B C D
False False False False
False True False False
True True False False
False False False True
False False False True
False False False False
False False False False
False False False False

DataFrameafterremovingduplicatevalues

A B C D
1.0 10.0 100 1000.0
2.0 None 200 2000.0
None None 300 3000.0
4.0 40.0 400 None
5.0 50.0 500 None
5.0 50.0 500 5000.0
7.0 70.0 700 6000.0
8.0 80.0 800 7000.0

DataFrameaftercappingoutliers

A B C D
1.0 10.0 100.0 1000.0
2.0 None 200.0 2000.0
None None 300.0 3000.0
4.0 40.0 400.0 None
5.0 50.0 500.0 None
5.0 50.0 500.0 5000.0
7.0 70.0 700.0 6000.0
8.0 80.0 800.0 7000.0

SubsetofDataFramewithcolumnsAand B

A B
1.0 10.0
2.0 None
None None
4.0 40.0
5.0 50.0
5.0 50.0
7.0 70.0
8.0 80.0

ENROLLNO:-12302040701118 PAGE|43
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

Subset ofDataFramewithrows2 to4

A B C D
None None 300 3000.0
4.0 40.0 400 None
5.0 50.0 500 None

Subset ofDataFramewith rows2 to4andcolumns0and2

A C
None 300
4.0 400
5.0 500

Meanofeachcolumn

Column Mean
A 4.571429
B 50.0
C 437.5
D 4000.0

NormalizedDataFrame

A B C D

0.0 0.0 0.0 0.0

0.142857 None 0.142857 0.166667

None None 0.285714 0.333333

0.428571 0.428571 0.428571 None

0.571429 0.571429 0.571429 None

0.571429 0.571429 0.571429 0.666667

0.857143 0.857143 0.857143 0.833333

1.0 1.0 1.0 1.0

ENROLLNO:-12302040701118 PAGE|44
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-10
Prac-10:

WriteapythonprogramtoperformdatavisualizationtroughMatplotlib. In[1]:

[Link]
import pandas as
pd import numpy
as np
importseabornassns

[Link](42)

data = {
'Category':['A','B','C','D'],
'Values':[Link](10, 100,4),
'Scores':[Link](50,10,4),
'Quantity':[Link](1,10,4)
}

df = [Link](data)
print("SampleDataFrame:")
print(df)

[Link](figsize=(8,6))
[Link](df['Category'], df['Values'],
color='skyblue') [Link]('Bar Chart of Values by
Category') [Link]('Category')
[Link]('Values')
[Link]()

[Link](figsize=(8,6))
[Link](df['Values'], labels=df['Category'], autopct='%1.1f%%', startangle=140,
colors=sns.color_palette("pastel"))
[Link]('PieChartofValuesbyCategory')
[Link]()

[Link](figsize=(8,6))
[Link](df['Category'], df['Scores'], marker='o', color='green')
[Link]('Line Chart of Scores by Category')
[Link]('Category')
[Link]('Scores')
[Link]()

[Link](figsize=(8, 6))[Link](df['Values'],
df['Scores'], color='red') [Link]('Scatter Plot
of Scores vs. Values')

ENROLLNO:-12302040701118 PAGE|45
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

[Link]('Values')
[Link]('Scores')
[Link]()

data=[Link](1000)
[Link](figsize=(8, 6))
[Link](data, bins=30, color='purple',
alpha=0.7)
[Link]('HistogramofNormallyDistributedData')
[Link]('Value')
[Link]('Frequency')
[Link]()

[Link](figsize=(8, 6))
[Link](x='Category', y='Scores', data=df)
[Link]('Box Plot of Scores by Category')
[Link]('Category')
[Link]('Scores')
[Link]()

df_corr = [Link]()
[Link](figsize=(8,
6))
[Link](df_corr, annot=True, cmap='coolwarm', fmt=".2f")
[Link]('Heatmap of Correlation Matrix')
[Link]()
[Link](df)
[Link]('PairPlotoftheDataFrame',y=1.02) [Link]()

[Link](figsize=(12,8))
[Link](2,2,1)
[Link](df['Category'], df['Values'],
color='blue') [Link]('Bar Chart')
[Link](2,2,2)
[Link](df['Category'], df['Scores'], marker='o', color='orange')
[Link]('Line Chart')
[Link](2,2,3)

ENROLLNO:-12302040701118 PAGE|46
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603
OUTPUT:

Category Values Scores Quantity


A 61 38.021936 5
B 24 71.416584 4
C 81 49.053790 8
D 70 40.711719 8

ENROLLNO:-12302040701118 PAGE|47
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|48
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|49
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|50
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-11
Prac-11:
WritepythonprogramforadvanceddatavisualizationthroughSeaborn.

In[1]:

importseabornassns
import pandas as
pd import numpy
as np
[Link]

tips=sns.load_dataset('tips')
[Link](style='whitegrid')

[Link](figsize=(8,6))
[Link](x='day',y='tip',hue='sex',data=tips,split=True,inner='quart',palette='muted') [Link]('Violin
Plot of Tips by Day and Gender')
[Link]()

[Link](tips, hue='sex',
palette='coolwarm') [Link]('Pair Plot of
Tips Dataset', y=1.02) [Link]()

[Link](figsize=(10,8))
corr_matrix=[Link](numeric_only=True)
[Link](corr_matrix,annot=True,cmap='coolwarm',linewidths=0.5)
[Link]('Heatmap of Correlation Matrix')
[Link]()

[Link](figsize=(8,6))
[Link](x='day',y='total_bill',hue='time',data=tips,palette='Set2')
[Link]('Box Plot of Total Bill by Day and Time of Day')
[Link]()

[Link](figsize=(8,6))
[Link](x='day', y='tip', data=tips, color='purple')
[Link]('Swarm Plot of Tips by Day')
[Link]()

g=[Link](tips,col='time',row='smoker',margin_titles=True)
[Link]([Link], 'total_bill', bins=10, color='teal')
[Link]('FacetGridofTotalBillbyTimeandSmokerStatus',y=1.03) [Link]()

jp = [Link](x='total_bill', y='tip', data=tips, kind='reg', color='green')


[Link]('JointPlotofTotalBillvsTipwithRegressionLine', y=1.02)
[Link]()

ENROLLNO:-12302040701118 PAGE|51
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

[Link](figsize=(8,6))
[Link](x='day', hue='smoker', data=tips, palette='coolwarm')
[Link]('Count Plot of Days by Smoker Status')
[Link]()

[Link](figsize=(8,6))
[Link](data=tips,x='total_bill',hue='time',fill=True,palette='crest',alpha=0.5)
[Link]('KDE Plot of Total Bill by Time of Day')
[Link]()

[Link](figsize=(8,6))
[Link](x='day',y='tip',data=tips,jitter=True,hue='sex',palette='Set1',dodge=True)
[Link]('Strip Plot of Tips by Day with Jitter')
[Link]()

OUTPUT:

ENROLLNO:-12302040701118 PAGE|52
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

ENROLLNO:-12302040701118 PAGE|51
MADHUBENANDBHANUBHAIPATEL INSTITUTE
OF TECHNOLOGY
(ACONSTITUENTCOLLEGEOFCVMUNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PYTHON FOR DATA SCIENCE: 202045603

PRACTICAL-12
Prac-12:
ExploringGoogleDataAnalyticstool.

SOLUTION:

ENROLLNO:-12302040701118 PAGE|52

Common questions

Powered by AI

Updating a tuple with new values involves converting the tuple to a list, making the necessary changes, and then converting the list back to a tuple. For example, if you have a tuple my_tuple=('Maths', 'Science', 'History', 'English'), you can convert it to a list, modify the list (e.g., change 'History' to 'Geography' and remove 'Science'), and then convert it back to a tuple. This process leverages the mutable nature of lists since tuples are immutable .

You might also like