You are on page 1of 262
Ormatics practices a text book for class XII Informatics Practices is a major subject at Senior Sec ‘computer practices that apply various fields. The subject of Information Science apy Language Python with an aimtouse itt effectively management o Written strictly according to CBSE syllabus of subject code 065, book covers * Data Handling + Database Query using SQL + Computer Networks + Societal Impacts This text book has been so designed that it contains ade« Keeping in syne with e: friendly presentati and fun in. Thi OTQs (01 assignments - promises to guide you for the preparation examination Publisher $991}9e1d SOIYEUOJUL 1X Ailey: a ARTA) informatics practices SUMITA ARORA PRO aCe [oye Published by GAGAN KAPUR Dhanpat Rai & Co. (P) Ltd, Det Seles Office : 1710, = Soret oa Repl. Ofc 4576/5, Agarwal Road Darya Gan New Dethit10002 ‘Phone ; 2324 7796, 37, 88, dhanpatriegmail.com Preface manent but change’. Everyone agrees to this and this reflects inal EDITIONS : 2002, 2003, 2004, 2005, 2006, 2008, 2010, 2013, 2015, 217, 2018 ‘REPRINT 2007, 2008, 2011, 2012, 2016 TaURTEENTA EDITION : 2020 Syllabus The SIPO app for Dig linked with this Distribution of Marks vn i a 1 Dats Handy ang Panda sd Dat Vi 38 2 ie ue ng SOL s eras race eed o 4 ‘Sonal ipa 08 oe eae » - + Purpose of ploting: drawing and saving following types of plo using Matpoti ine plot, bar graph, ‘hstgeam, pi chart Fequency polygon, box plot and seater Pot + Customizing pot: aot, syle dashed, dete width adding label tte, and legend in plots. Unit 2: Database Query using SQL Ormace se tain + Math fits FOWER(), ROUND(). MOD() 4 Text anit: UCASE( JUPPER() LCASE( JLOWER() MIDY YSUBSTRING( YSUBSTR), LENGTH), LEFT(, RIGHTY) INSTR), LTRIMG),RTRINO, TRIM) Joa [\j pears and en, ‘with Love Unit 3: Introduction to Computer Networks Impacts (4 Theo) cp ean xmmuniaton eu ata proto, nelle propery his, % plagario,tensing and copyright fee and open source software (FOSS), ersine soa faking phishing cyber bullying overiew of Indian FT Act eee - Eseate hazards and management + Awarenes about health concerns related to the sage of technology. Project {Learercan use Python ibrares oftheir choice to develop software fo thet school or anyother soil goo. ‘eames should be sensitized to avoid plagiarism and violation of copyright issues while working on Proje. Teachers shoud tke necessary suitably referent. c Tics con be done individually orn groups of 2t03 students. The projet shoul be started by students ‘east 6 months before the submission deadline ae measures for this, Any resources (dat, image et) used in the projet must be Practical Unit Name ‘Programs using Pandas and Matplolib t SQL Queries i Tiss le nlnimum of 20 programs based on Pandas 3 based on Motpotib and 20 SOL querie must be includes), Poet Work (using concepts leimed in class XI and XID) ViverVor Replace all missing values ina Importing and exporting data between pandas and CSV fle 13, Importing and exporting data between pandss and MySQL datsbase the schoo! result at, analyse the performance ofthe stents on diferent parameters, subject wise or dass wie. 3 the Data frames created above, analyze and pot appropriate chats with ie and legend. d] 16, Take data of your interest fom an open source (eg, dita gov) aggregate and summarize ‘Then plotting diferent ploting functions of the Matplot iteey, date of birt). 126, Write a SQL query to onde the (student 1D, mars) table in descending one ofthe maks Introduction to Computer Networks 7 Download ntl and configure broweon a— 2 Contents” Python Pandas ~1 242 Song Dame Vac 118 263 Aggregation 121 27. Wandling Missing Dat 271. DesetingFlering Msng Dats 123 272 Haring Maing Data ~ Dropping Ming Vacs 124 273. Handng Mesing Data Filing Mising Vs 128 ling ous fom ote tarot 126 28 CombiningDatFrames 281 Combining Dts wing cnet) 27 282 Combining Desay oil) 128 253. Conning Datamestcng eget) TE 29. Function groupty() Plotting with PyPlot ‘31. WhtisData Visualization? 32. Using Fypotot Matpotib Library fie 321 tinged nperting mati 162 fas 322 Wirt ite Pe Maids 165 33. CrestingLine Charts and Seater Chars 321 Line Chart wing plat) Feet 165 232. Spiing Pt Sean Gt 152 333. Applying Vans Stine pl) Fenton 169 224 Crating Str hare US 134 Creating Bar Charts and Pie Charts SAI Cheging Wl of te Brine Bar Chart 184 SAD Cheng Calor of the Barn Bor Chart 185 343. Crating Malle Bar Chart 288 44. Cratng a Horzonsl Bor Chet 11 345. Chtng Pe Charts 151 35. Customizingthe Plot ‘381. Anatomy ofa Chart 188 B52 Adding a Te 19 185 Sdecing Acesing Individual Vale 46 | 19. Adaing/ Modifying Rows /Column¢ Values in DataFrames f Cretng Data uit Ber Indes 58 41312. Acct Rove from Datars it Basen Dudes 55 Python Pandas ~ I! QB beteten 8 : [353 Seng Xand Lael Lin nd Tike 109 254 Ading Lge 205 355. SmintsFgue 207 36 resting Histograms PyPlot 137. Creating Frequency Polygons 38 Creating BoxPios a war a7 161 162 ae 208 aa as 245-277 279-308 Importing/Exporting Data between CSV Files/MySQL and Pandas 442 eteduction 4.2 Transfering Data benween csv Files and DataPrames 444, Exporting aDataframe'sDataas Table in MySQL Database MySQL SQL Revision Tour 51 Inoducton 52 Relational Data Modet Popular Relational DataBase Management System 581 ASL en SQL 282 55 Creating Tablesin MySQL 56 InseringDatainto Table 57 Making Simple Queries through Select Command 522g Al Dats 286 572. Seeing Patr Rows 268 573. Siting Periaar Clons 285 374 lating Reandot Dat (ith Keyond DISTINCT) 285 S25. Slesing From Al the Rew = ALL Keyword 245 525 Viewing Smtr of Tate 203 522. Pofering Spe Claatons 286 578 Using Colin Alay 2 529° Condition Based ona Rene 286 5720 Condition Base on List 286 $75 Condon Bad om Pater Matches 286 52512 Search fr NULL 267 58 Cheating Tables with QL Constraints 581° SQ Comins 248 513 Atering Tables 514 Dropping Tables aa 24s 26 27 264 29 200 zi ae 262 203 2a 204 293 293 298 294 295 399 — 424), ‘MySQL Functions 61 traduction 62 TextFunctons 63. NumericFunctions 64 Date/Time Functions Querying Using SQL. 72 Introduction 172 Ordering Records in Result- Order by Cause 221. Recing SOL SELECT ORDER BY Case 333 722 Onderng Dats on Mu 723. Onding Dato te 73. Aggregate Functions 7A TypesotSQL Functions 75 GrovpingResult-GROUPBY 751. Nested ros ~ Grouping om Mali Clemes 342 252 Pacing Conon on Grupa HAVING Clase 30 753 NowGrup Expasions th GROUP BY 344 Joins and Set Operations 81 Introduction 82 Joining Tables {829 Jong Tee asin OWN Clases of SQL SELECT 372 183 PerformingSET Operationson Relations £32 UNION 377 832 MINUS Opentor 380 {833 INTERSECT Oper 382 Introduction to Computer Networks ‘94 Inteoduction 92 Computer Networks ~Antntroduction 221 Conponentsof Com 93 TypesofNetworks 305 306 315 219 a3 333 37 340 340 361 364 399 400 402 94 Network Toolos ‘341 Pinot Lik 45 104 Seis Pr by Seer 429 105 Rte 1051 Elon f URL 80 1052 URL Types 42 106 Website 1061 Components of West 433 107 WebPages ponents of Nepage 434 2 Types of Wb Page 438 "3 Direc keen «Webpage ad Website 437 Voice Over tate Prot 40 125 25 26 429 430 44 Societal Impacts ‘res and Darin of Open Sure Technegy 465 Crime 18 CyberLaw andi Act 119. E-Waste Management 1191 E-te Disl Peas 472 1192 Beni ofeWate Recyting #72 11.10 Health Concerns with Technology Usage Data Protection MySQL ‘AnpendiB: New Sje: String Templates wit Answers to Objective Type Questions (OTQs) —n 455 456 47 45a 461 47 470 nm 7 43 a8 a2 97 wa 0-@) Lists OF QR CODES Lists OF QR CODES Pandas’ data structures in action 3 Series attributes in action 13 Vector operations in action 27 ‘Arithmetic in series in action 27 DataFrame Anatomy in action 28 DataFrame Attributes in action 38 Subset from a dataframe in action 43 For selective assignment solutions 69 Working of iterrows in action 77 Working of iteritems in action 79 Operations on dataframe in action 87 min( ), max( ) functions in action 87 mode( ), mean( ), median( ) functions in action 89 count( ), sum) functions in action 93 quantile( ) function in action 95 cumprod( ), cummax( ), cummin( ) functions in action 104 pivot( ) function in action 110 pivot_table function in action 116 coneat{ ) in action 127 join( ) in action 129 merge( ) in action 134 For selective assignment solutions 156 Line, Scatter charts in action 165 marker types in action 173 Scatter( ) function in action 179 Ber charts in action 163 Pie charts in action 195 pomiaat) sta inaction 199 boxplot( ) ae enna in action 218 For selective assignment'solutions 242 Lists OF QR CODES Pandas data stuctres in acton 3 veto of Anthmetic in eres in action DataFrame Anatomy in acton DataFrame Atroutes inaction 3 Suset om a datatrame in action 43 For selective assignment solutions. 69 ‘Operation on catattame in action 81 ring), max{ ) functions in acton 6 mode), mean) madian()uncbons in action 89 table functon in action merge) acon 134 For selective assignment solutions *$6 Line, Satter chan inaction pes acton cater) fa rans i acti ‘assignment'solutons 24 Copter 1: PYTHON PANDAS ~ 1 arrays in which the rows and columns canbe identified and accessed with labels rather then simple integer indices You willeam about tin this chapter. Ost of many data structures‘ of Pandas, £0 and DataFrame- ate universally popula for their dependability. Before we proceed to the detailed discussion of Pandas Series and Dataframe, let us talk about the basic difference between the two. huge tabular data sets comprising different data Pandas on tecnica patiorm of your coitus + Sizeimmutable i, size ofa Series cbzet | + Size-mutable, ie, sizeof a Dataframe nce create, cannot change. Ifyou wank | object. once create, can change in place. foaldldrop an clement intemally anew | That you can add/drop elements in an Series objet willbe erated. existing daarame object For working in Pandas, we generally import both pandas and mumpy modules/ibraries by siving following import statements on the Python shell or in the script or program code : You cm a ay ei ae in place ea np Bt Amport pandas 28 94 ~~ pf aad mp hae ben prefered haces gemally Anport nunpy 3s np “After this basic introduction of Series and DataFrame objects, let us talk about these individually ‘A daasrctar i peta wy of rig ond rang dain comps ep on eased edith inept Let a + rte code flowing cases 3s offers many data structures variety of data. At the ‘ ata. At the very basic level, Pandas data structures can be thought of somewhat as enhanced versions of NumPy structured bout the ways to create Series objects as per above syntax : q co Simplest way to rete Serie type object isto give a sequence of values as attribute to Series) eves? data structure of pandas. It represents a ‘of indexed data. A Series type object has Series is an impo ‘one-dimensional ‘heo main components ‘© an array of actual data ‘9 an associated array of indexes or data labels. Both components are one-dimensional arrays with the same length. The index is used to access individual data values, eg, following figure 1.2 shows some series objects: serdar Oufeces= Serkan any Python HeaUeNCED 1t will return an object of Series type. For instance, consider following example statements that ‘create two Seris type objects using some Python sequences: ta Es ee 1.4.1 Creating Series Objects A Series type object can be created in many ways using pandas library's Series(). Make 3 you have imported pandas and numpy modules with import statements. ‘As you see above, if you just specify the sequence or just the values with Series) and no index, then by default index array consists of the integers 0 through N ~1 (where Nis the length of data). |. Create empty Series Objet by usi ih no parameter EXAMPLE EU) White code to cesta Serie object using the Pylhon sequence, 68, 10) Assume that Pandas is Imported as ais name pa. SOLUTION Theabove statement wil reat an ep Ser type objet with no value having det which is float64. Consider foll = ei |. Creating non-empty Treat nonempty Series objects, you need to specity arguments for data and in ‘syntax ‘Pandas is imported as alas name pd. SOLUTION a valid Numpy Preps datatype and data is the data part ofthe Series object it (Caple 1 PYTHON PANDAS = 1 DOMME WY Wes param waa Se tg on MY Outpt Pat hs oe he ege foe SOLUTION AAnport pandas as pd ‘Sertes (np-Linspace(2A, 64, 5)) Sane EY accra Bers tg li een Pe peel es nme at Wie a program to ease w Seve object wing am vdarvay that is erested by ting 2 Uist (3.5), Output (ii) Specify dota os o Python Dictionary “The sequence that you provide with Series() can be any sequence including dictionaries, Letus see how you can create a Series object by specifying indexes and values through a dictionary. (see below) Assume that Peni imported sais name pd SOLUTION (i Specty date 0s on ndorroy ‘The data atribute ean bean ndarray also aoe Her, one thing is noteworthy that if you are creating a Series object from a dictionary object, ies then keys ofthe dictionary become index of the Series and the values of dictionary become the ies object. Als, the indexes, which are created fom keys may not bein the same onder as you have typed them. each section of lass 12 in your schol. You ean also combine the code lines Not bine the code lines of SOLUTION ‘Carefully read the following: series np:arange( You can cese a Seis camp tat dee the san 5 Objects panda Sates index None, data mefunction expressions )) ‘To understand its functioning, consider following example statements, caution ! specifying indexes exp using an index sequence, you must provide Indexes ‘ales in data aay, providing to few orto many indices will lead 0 an ero ade focreatea Series oj that stores the contribution am SOLUTION ‘The vectorized operations on a NumPy array (eg, a" 2 or a "2 ) will be applied on every ‘of NumPy array and stored as data part of Series object. Now consider another code: spel aay te rear datype to tore iE you can pel your own datatype by speciyng Nonny etatype with BPE ‘The above code tries to create data array for Series object obj8 by giving expression 2 *Lst where st isa Python list and as you know a number multiplied with a list replicates the list those ‘many times and hence the data array has the same lst values replicated twice (: 2* Lst). A Coole PYTHON PanoAs = 1 {s similar yet different from the previous example, Te section names CK, B,C ‘DY, E) and contrition iy. Your school has decide to donate as much ly read the following example. It Carefully 3 Series Object Atributes When you create a Series type object al information related to itis available | ser wren {through attributes. You can use these attributes inthe following formatto get | _ #277 ae &: informa 7 listed inthe table below. these attrbutes follow the Table 12. ole rade tem rect (5700, Conran a made by exch section he dol stu the dype object ofthe underying data tet 2 tuple of the shape of the undying data ‘Series ebsect.nbytes | eum the numer of tsi the underlying data Series objectndin | rerum the number of dimensions of te underlying data - ey Series objects stze | rerum the number of elements in the underlying data [cise i: Sectesobjec> Atestze| eum the ize ofthe ype ofthe item ofthe undying data enya ta athe ‘Series abject hanans | eum rif here are any NaN vals otherwise retuen False (ja nds regres tee Series cbject.egty | ret Tras th Series eet is empl. ae otherwise eee reed pecty a0 iceger toe, Pandas a les show how to view various attributes of Petco Following examples show how to tributes of Series object. asonatcay) because Nat Retrieving Index Arroy (index (clues ottibute) of o amy mene (0) Retrieving Index Arroy (index ottibute) & Doto Arroy (values attibute) of a Series Object Serato Noucanccesthe indexaray and ata values aray of an existing Serie objet ob a8 shown "> While creating a Series object, when you give index array as a sequence then there Compu fre nue of dee That you can have platens nthe index rep and Python wont tae ony eno ep ate figure below a ‘Chopler 1 PYTHON PANDAS = 1 ing Doto Type (dype) ond Size of Type (itemsize) 4 se tr miner © Similarly, to check if Series object contains some [NaN value or not, you can use hasnans attribute {as shown below (using objects of reference 22) ‘© You can use Ien() to get total number of elements and .count() method with Series object to get the count of non-NaN values inaseries object, ‘To know about the number of elements in the Series object, use size. ‘To know total number of bytes taken by Series object data, use nbytes ( ‘equal to the size * itemsize) >>> ebj2.ndie Fi Solas di SOLUTION >>> print (obj2.size, obf3.size) 43 ——_—_——_ * >>> print (obj2.nbytes, ObJ3.RDYEES) 9 hs sme, ee 32.24 eT hee fe) Checking Emptiness (empty attribute) ond Presence of NoNs coat have created an empty Series abject namely obj also and then checked emptines ith emptiness chet ab and ob 0fRefeence 12 (given on previous poge)> eine Series Ti vis se — ; cae was nav : empty? Ceapty) 2 False False CChoper 1 PYTHON PANDAS 1 2. Extracting Slices from Series Object 1 Series Object and its Elements e too from a Series object to retrieve subsets. Let us see ies objects. Here, you need to understand an important lke 1,2 3and won. (ee Fg 1a) obs Position “index Dota ‘igure 1.3 Some sample panda Stes Objects. For all the following operations we shall be using the sample objects shown in Fig. 13. ‘As you sce in above figure, we have use only valid oF ‘object to access an element. ee All other rules of slices apply, i, you can specify steps, you can reverse the elements, the range of INFORMATICS PRACTICES ~ 3 CChopler T= PYTHON PANDAS = 1 Renaming Indexes The size of new index array must match with existing index atray's size. In other words, you cannot change the size of rnumber of indexes 1.4.5 Operations on Series Object ‘Lets now talk about how you can perform various types of operations on Pandas Series objects. 1. Modifying Elements of Series Object ‘The data values ofa Series object can modified through item assignment, ie, Output Series abject after nodifying amounts: X *s anount 1s °C* and *D'*s anaunt ‘object after modify import pandas as pd : # trdata objects creation or loading happens here A sample Series object lowing all are legal 00242, 0b2*3, ob ob2*¥2, ob2>15 ete. . age came Eee = as ‘on two corresponding items of speration is performed only on the ‘will perform arithmetic only with objects having 0,12 indexes for all other produce NaN (not a number). ‘Also, if the data items ofthe two matching indexes are not compatible for the operation, it will return NaN (Not @ Number as the result of those operations. ‘Tounderstand this, consider below given (Fig. L.6) five Series objects ob1, ob2, 063, ob and obS {obt and ob3 have matching indexes ; ob2 and obS have matching indexes; obs has some Figue 16 (a) Some sale Svcs objet with matching and non-matching indexes | 2 INFORMATICS PRACTICY Chater 1 = PYTHON PANDAS —1 [Now carefully look at the statements carrying out arithmetic operations on objects ‘matching indexes (ee bel 3 EXAMPLE BUM Nannberofstadents in clases 1 and 12m re stems (Scene, Commerce and Human are stored in to Sve object 1 and 12, Writ coe SOLUTION Output ‘Same ting i spose expression ob +05, le comesponca ves finda’ re add, simlay caesponng vals of esse ade, ad 50, ‘Dic Population sores the details of population in four mcr cites of Indix and Objet? UAvglncome sores the foal aeage income repre in previous year in enh ofthese metros. Calculate income per ita foreach ofthese metro cites, ‘Sermo ain mar Dont pe file rae ‘Seni na py le ater ph ke SOLUTION iene <~ See how easy it has become to calculate Income if we have huge data stored the cities and average income etc. ‘Then ob6 will also bea Series object (if ob1 and ob3 are Pandas Series objects) INFORMANTS a (chose Ts PITHON PANDAS = 25 DANPLE ‘Soves bet 1 sors the charity contribution made by each section (see Below): Boolean type (es ra ey) Ki A 6700 B S600 C5000) > 5200 | Write program to display which sections made a contribution more than €5500/- | soLUTION Output Pa contribution > S500 by = : & 6700 print 3 sc print (533 type: ints 6 Sorting Seri You can, values ofa Series object onthe basis of values and indexes. Sorting on the Bos “To sorta Series object on the basis of values, you may use sort_values( ) function as per the following index: a Orit pet ‘Series object> sort_values([ascending =Trie]Fatse]) ending is optional an if skipped it takes the vale Tre by default. Se eg ar er eneeeatie SESE BE Se ett es ed aot ns Be | peso as rage easiest acing ey da For example consider the Series object s11, >>su (ascending = False) eee | elses sorted i descending order | type: intea Values sorted in ascending order To sort values in descending order, you may (default setting) write sort_values(ascending = False) T nFORMATICS PRACTICES — 26 Sorting on the Basis of Indexes: een oe ees on tn bass finders You may we SHINES finetion 8 p amas oo Od opm selFalse)) sipped, it takes the value True by default. sop sta. sort index ascending = False) > 5200 5008 ean 2 >> atf2 =u ct, index o> def ~ Narks Sport students 1 79.58 Cricket Ruchika IT 83.75 adninton Neha HHT 74.09 Football — Mark IV 88.50 Athletics Gurdyot V__99.00 Kabaddi Janaal tn pe pe 2a ses he inde eqn Python wl ake indexes rom the index sequence, BUT the umber of indexes given inthe index sequence MUST MATCH the length of eitionary’ oer Python wil giver (elon) Sh oF Scbonary” CChaper 1 = PYTHON PANDAS —1 31 mam Given a dictionary that stores the section name’ Tit as walue for Section” key and contribution ‘amounts list a elue for ‘Conte key : dictt = (‘section O'], "contri: [ 6700, 5609, 5200, 5200} Output Write code to ereate and display the data frame using above dictionary a SOLUTION import pandas as pd contri section 0 6 dict = (‘Section 1 560008 "contri": [ 6780, 5600, 5000, 5200] } 2 soo 0c \df4 = pd. DataFrane(dict1) 3 52000 print (aft) (0) Creating © datafrome from © 2D dictionary having values os dictionary objects A2D dictionary can object using such 2D. Given 22D. ‘You can create a DataFrame by passing this dictionary : a >>» pd.DataFrane(people) Marketing Sales <_Oadsiompiewascsumes_] age 22 rane Neha Rohit sex Fenale Male ‘This time the keys of inner dictionaries make the indexes and the keys of outer dictionary make the columns. ‘Greate and dlspay a DtaFrame fom a 2D dictionary, Sales, whch Hors Pe guartr ose ales 8 shown blow tra" : 34500, "gtr2" : 56000, “Qtr3* : 47000, “gtra* : 49800} , {'Qtra" :a4900, *Qtr2" : 46109, “Qtr3": 57002, “Qtra* : 59000 }) SOLUTION Anport pandas as pd Sales { ‘yet" :{‘@tra" : 34580, ‘¢tr2" : 56900, "gers" : 47090, "¢tna* : 49900 }, “yea: {Qe : 44900, “Qtr2" : 46100, "Qtr3" $7009, “Qtra? : 5920} dfsales ~pd.batatrane( Sales) prine(afsates) Output ye yea ‘cert 34500 “44900 aqer2 $6000 46100 er3. 47000 57000 ‘tr 43000, $9000 T ste op of al nner dictionaries (71 2) ae exay stove eam noise one UNG Te bjt sales also has the same numberof fm number and names th INFORMATICS FRACTICES — b team co ad there been a situation x have done following things a been total number of indexes equal to sum of unique inner Keys in vhere inner dictionaries had non-matching keys, then in that () There would have (o Forakey cused to depict the missing values. vo» Collect={ >>> collect = ("yr yp> Collect =( ‘T's Collect, ‘11':Collect2} >>> df= pd.DataFrane(collect) vod x Fa wow “ie ran bore ae yl 3500.0 2200.0 Name tet erent art yz 500.0 NaN Carly ad the loag cole “qtra' : 46100, "93" : 57800, "98" : 59000) 1000, “Qtra’ : $7800} (F3 = pd.bataFrane(diSales1) ‘the index labels of the Date df the colon names of SOLUTION (The index labels of 48 will include : A, B, Q3, Q4, Qtrl, Qu2, Qtrd. The total number of indexes is equal to total al unique inner keys, ie, 7. (The column names of 43 will be: 1, 2 " di woud ue Nal values to *p2nsing ves or ake are mien In sy inner | chapter 1s PTHON PANDAS —1 2. Creating a DataFrame Object from @ Li >> import pandas as pd >>> topper { "Roll >>> topperd = { "Rolo >>> topper = {“Rolino" >>> topper = {*Rolno" | >>> toppers = [topper tr | —e >>> topof «pd. DataFrane toppers) >>> topoF ropperc, topperD] +i att of etioaries @ 1s Pavni 97.5 1 236 Rishi 98.0 2 307 Prect 98.5 3 422, Paula 98.0 ‘When a DataFrame is created with alist of dictionaries, the columns are created from the keys of dictionary elements and default indexes are assigned to rows (0,1, 2,3...) as you can see above. You can specify your own index labels through the index argument containing the 236 Rishi 307 Preet. of #22 Paula ‘Wiltz a program to cata datajame from alist containing dictionaries ofthe sales performance jee €*,"SeeD"] ) eee ea sores Output Target Sales —— sos a St sree ana omel cnc, i si ia cet fom tas fern me cre Tn a Soe ica etree | SSeS eal a SeleOF «pd.DataFrane(sales , index= ("zoneA’, "zoneB", ‘zoneC, print( saleDF ) roan 34 ng ists wil lo rete a dataframe where 2c |, (88, 98, 56) ] ont ea 2 0 5 45 60 138 67 88 2 88 90 56 With 20 lists the created dataframe by default names the columns and indexes as 0, 1, 2.. unless you specify the index and columns arguments. You can specify own index sramesfabels with index argument and columa labels with columns argument in the ‘DataFrame( as illustrated in following two examples. iran to real a date from a 2D Wt. Spey oun inde abel Soumon 013") Output Ota saa 3 4 60 oT 8 56 EXAMPLE BI Write «progr to create data containing 2 Tit, ack conta sctual Sales figures of four zoral offices. Give appropri Sowwnion rint( 2sale0F ) Output 004 Target 5600 Sales CChopler I: PON PANDAS 1 35 3. Creating @ DatoFrame Object from a 2-D ndoreay You can also pass a two-dimensional NumPy array (ie, having shape as (<1e, <1) t0 Dataframe() to create a dataframe object. |» 4 5, 6], np-snt32) fie, 0 onwards, ‘You can however, specify your own column names and /or index names by giving a columns sequence and/or index sequence >>> dt2= pd.DataFrane(narrty colunns = [‘One", "Two", “Three"]) pooate2 (\ us a2 40.0 50.0 \cf 22a 301.5 cdt3= pd.DataFrane(arr2) print (dt#3) Output » 226, 217), folpetania} 0 101 113 124 1 130 140 200 2 m5 216 217 37 from a 2D Dictionary Objects sing multiple Serie objects, In a2D dictionary, you rd then you con pass hia dcionary as argument to o> dt a= pd.bataFrana( school) Now the DataFrame dt, created above, will be lke Soves objet tht stores aceage salary er branch and then creste @ DataFrame Write a program to erat object fom Bese Series objects SOLUTION import pandas as pd Output 5. Creating a DatoFrame Object from another DotoFrame Object ‘You can pass an existing DataFrame object to DataFrame() and it will eeate another dataframe object having similar data, Consider the code shown below that passes to DataFramet ) another dataframe object. INFORMATICS PRACTICES — 38 Given a DataFrame object dtl: pep dtél o12 e123 1456 ‘You can create an identical dataframe by passing its name (dtil) to DataFrame( ) >> aa Marketing sales age 25 2 name Neha Rohit sex Female ale (0) Retrieving Various Properties of a DalaFrame Object P To view the value ofan attribute, give its name with the dataframe’s name as depicted in flowing examples >>> df. index oo dtn.stze ndex((2ge", ‘ane’, “sex, type object") ‘ >>> afnacolns Doo df. shape Index([ "Marketing", 'Sales"], dtype= ‘object') (3,2) “ : cae a >>> dfn.ndim >>> dfn.axes 2 >o>dfnempty False Cindex({'age', ‘nane* Index({['Marketing’, ‘Sal >oodfn.dtypes Marketing object Sales object type: object sex'], dtype= ‘obgect”), J. dtype = ‘object')] (6) Getting Number of Rows in a DataFrame ‘The lenteDF object) will retumn the number of rows ina dataframe eg, o> Ten( dn) 3 (€) Getting Count of non-NA Values in DataFrame Like Series, you can use count() with dataframe too to get the count of non-NaN or non-NA. i count() with dataframe is litte elaborate If you do not pass any argument or pass 0 (default is 0 only), then it retuums count of non-NA values for each column, ¢2, >>> df. count) >>> df.count (axis = "index") Marketing 3 Marketing 3 sales 3, Sales 3 type: intea type: ints ‘You may also pass argument axis = ‘index’ to get the same result as above, (i) you pass argument as 1, then it retuins count of non-NA values for each roW, ¢. >>> dfn.count(1) >>>dfn.count(axds = ‘colums") age 2 ccm age 2 mane 2 __inonintansecoumns) ane 2 sex 2 wil padics he samereaut 7” sex. 2 type: ints type: inesa ‘You may also pass argument axis = ‘columns’ to get the same result as above, y InFoRMATICS FRAC snns by using attribute T as (d) Transposing a DotaFrame a dataframe by swapping its indexes and col EXAMPLE DataFrame and its rasp SOLUTION Pe ouput onsite a le 0S snr = 3 wore 22 cs age as 2 3s 2 vam Anny arts at os wie es stp (e) Numpy Representation of DotaFrome You can represent the values of a ject i i the values ofa dataframe object in numpy way using oalues attribute : type object) hope 1: PYTHON PANDAS — 1 1.8 Selecting or Accessing Data ‘objet you can extract or select desired rows and columns as per Your us see how. ples in this section, in coming lines, we are using the following DataFrame dtf5: DataFrame : aus Po Hospitals Schools Delhi 0 a9 7016 208 3508 19 728 357 7617 1.8.1. Selecting/Accessing a Column Selecting a column use the following syntax: ] <————— Unsure rts column nane> <————— ng det rte following example accessing columns Population, Schools from dataframe dtiS. >>> de#5['Schools"] 718 ses m8 7617 Nase : Schools, dtype : inté# ation") 30927986 feype: intes In the dot notation, make sure not to put any quotation marks around the column name, For example,

You might also like