Python - Part 2 - Read-write-
export & API - Rest API
Reading Files with Open : Module 1
1-Open Methode (Dont Use)
always use csv format as xml format can sent many error
myfile=open(“filepath.text”,”r”)
df=myfile.read()
myfile.clos()
2 - with open methode not pandas methode for writing in lines
(json case , csv ...)
with open (“filepath.csv”, r) as file1
df=file1.read()
print(file1.closed)
print(df)
3-write
fil1.write()> make input into file search!!!
4- pandas library open file for data scientist purpose
import pandas as pd
fl=”path.csv”
df=pd.read_csv(“fl”)
Case to use
A- CSV file
Import pandas as pd
file_path=(“filepath.csv”)
df=pd.read_csv(file_path)
df.head()
B-Excel file
file_path=(“filepath.xlsx”)
df=pd.read_excel(file_path)
df.head()
2- How to create your dataset
use dictionary
student_spe_meca_ufr1={”licence3”:[”amine”,”bechtaoui”,”tounsi”,”les
francais”],”master1":[”amine”,”bechtaoui”,”tounsi”,”les francais”],”master2":
[[”amine”,”bechtaoui”,”tounsi”,”les francais”]}
df= pd.DataFrame(student_spe_meca_ufr1)
3- Extract just 1 coulmn
Y=df[ [”licence3"] ]// example below student_spe_meca_ufr1 , we use double
brackets [[]]
4_ Extract 2 coulmns
O=df[[”licence3",”master1"]] / /or 3 or more
5- Change index
df2=df
df2.index[”2018",”2019",2020"]
9 - Extract dataframe
Z1=df.iloc[0:5, 0:3] // 6 first rows start from 0 index and 3 first coulumn
start from 0 index )
Or
B1=df.iloc[0:2,”licence3":”master2"] // 0 1 2 rows and from “licence3” to
“master2” coulmn)
6- Methode unique
df[”licence3"].unique() > will extract unique entry
7- Deal with dataframe (extract only some data)
Girl Boys Succuess_ succes_bo total_class
girl ys e
2015 8 15 7 15 23
2016 11 14 9 10 25
2017 14 16 12 13 30
2018 16 20 13 17 36
Extract only statistics Boys 2016 up
import pandas as pd
file_path=”filepath.csv”
df=pd.read_csv(file_path”)
df.head()
a- extract only statistics after
df1=df[df[”total_classe”]>25] > // only after 25 of classe total will be shown in
dataframe
case extract some rows and 1 coumns
Assume that you have a data frame containing details of various musical artists, their
famous albums, their genres, and various other parameters. Here, 'Album' is the second
column. How do we retrieve records from row 3 through row 6?
df.loc[2:5,”Album”]
Application Program Interface API -
REST API : Module2
1- API
Its used to send request to library and library return result
2- REST APIs (communication via input reequest output
response )
Message sent via HTTP message contain json file
HTTP input HTTP
Request Request
JSON ( like dictionary) output JSON
How its work ?
import requests
url=’https://ibm.com/’
r=requests.get(url)
r.statut_code >200
header[”Content-type”]
r.text > display content
r.json > display json format