Y gweithgaredd hwn yw'r cam cyntaf wrth ddefnyddio Python i archwilio data.
Byddwn yn gweithio drwy bopeth gyda'n gilydd: cyflwyno taenlen i'ch rhaglen, deall sut mae'r data yn cael ei storio ac ysgrifennu cod syml i gael gafael ar y wybodaeth sydd o ddiddordeb i chi. Mae pob enghraifft yn datblygu'n raddol o'r un flaenorol, gan eich helpu i feithrin eich hyder gam wrth gam.
Drwy weithio drwy'r gweithgaredd hwn, byddwch yn dysgu:
Cliciwch ar y botwm 'Nesaf' i gychwyn.
Mae Tîm Allgymorth STEM Cymru wedi bod yn rhedeg rhaglen newydd lle mae ysgolion yn gallu archebu pecynnau dosbarth ymarferol i gefnogi gwersi gwyddoniaeth a thechnoleg. Mae pob pecyn yn canolbwyntio ar faes gwahanol o ddysgu STEM - Electroneg, Roboteg a Gwyddoniaeth Gyffredinol.
Dros yr wythnosau diwethaf, mae ysgolion wedi bod yn cyflwyno archebion, naill ai ar-lein neu wyneb yn wyneb mewn digwyddiadau cymunedol. Nawr, mae angen help ar y tîm i drefnu a dadansoddi'r wybodaeth hon er mwyn deall y galw, trefnu lefelau stoc a pharatoi danfoniadau yn y dyfodol.
Rydych chi wedi derbyn sampl fach o archebion diweddar.
Mae pob rhes yn y tabl isod yn cynrychioli un archeb o un ysgol, sy'n dangos:
| RhifArcheb | Sianel | PecynnauElectroneg | PecynnauRoboteg | PecynnauGwyddoniaeth |
|---|---|---|---|---|
| 201 | ArLein | 42 | 15 | 63 |
| 202 | WynebYnWyneb | 58 | 22 | 41 |
| 203 | ArLein | 37 | 18 | 55 |
| 204 | WynebYnWyneb | 12 | 47 | 72 |
| 205 | ArLein | 29 | 33 | 88 |
| 206 | WynebYnWyneb | 64 | 11 | 49 |
| 207 | ArLein | 23 | 9 | 70 |
| 208 | ArLein | 51 | 27 | 46 |
| 209 | WynebYnWyneb | 34 | 14 | 39 |
| 210 | WynebYnWyneb | 19 | 31 | 77 |
Sylwer: Gan ein bod yn bwriadu defnyddio'r set ddata hon o fewn rhaglen Python, mae'r holl fylchau wedi cael eu dileu. Fel dewis amgen, gallech ddefnyddio tanlinellu yn lle unrhyw fwlch, er enghraifft 'Wyneb_yn_wyneb'/'In_Person'.
1. Copïwch y tabl uchod i daenlen.
2. Pa archeb sy'n cynnwys y nifer uchaf o Becynnau Roboteg?
3. Faint o Becynnau Gwyddoniaeth a archebwyd i gyd?
4. Faint o archebion a drefnwyd ar-lein o'i gymharu â wyneb yn wyneb?
Nid yw rhaglen Python yn gallu cyrchu data yn ein taenlen gyfredol. Mae angen i ni felly newid y fformat i rywbeth o'r enw ffeil .csv - fformat y mae Python yn gallu ei ddarllen.
Ffeil gwerthoedd wedi'u gwahanu ag atalnod yw ffeil CSV.
Yn hytrach na storio data gyda lliwiau, ffiniau, fformiwlâu neu fformat (fel y mae Excel yn ei wneud), mae ffeil CSV yn storio testun crai y tabl yn unig:
A dyna ni. Dim nodweddion cudd. Dim nodweddion arddull. Dim ond testun plaen.
Oherwydd ei fod mor syml, mae bron pob iaith raglennu - gan gynnwys Python - yn ei chael hi'n hawdd i ddarllen ffeiliau CSV.
Mae hefyd yn lleihau maint y ffeil yn sylweddol o'i gymharu â maint taenlen.
Yn ôl â ni at ein taenlen, a gwneud yn siŵr ein bod ni wedi dileu unrhyw ychwanegiadau (fel swyddogaethau, cyfrifiadau neu gyfansymiau), ac yna dewis yr opsiwn Cadw copi/Save as o'r ddewislen ffeiliau.
Mae angen creu ffolder ar gyfer ffeiliau'r gweithgaredd hwn mewn man cofiadwy.
Yn y gwymplen, dewiswch Cadw copi/Save as type: CSV(comma delimited)
Rhowch enw i'ch ffeil (heb fylchau), fel stem_orders.csv
Cliciwch i arbed y ffeil.
Os ydych chi'n cael neges yn rhybuddio am golli nodweddion, mae hyn yn normal (dim ond testun plaen y mae ffeiliau CSV yn ei storio), a dewis Ie/Yes i barhau.
Os ydych chi'n chwilfrydig ynghylch sut mae'r data mewn ffeil CSV yn wahanol i'r data mewn taenlen, gallwch agor eich ffeil gan ddefnyddio Notepad.
Rydyn ni nawr yn mynd i edrych ar osod rhaglen Python i ddefnyddio ein ffeil CSV ond yn gyntaf, rydyn ni am drafod opsiynau meddalwedd ar gyfer ysgrifennu rhaglen Python.
Os oes gennych chi feddalwedd golygu eisoes, mae croeso i chi sgrolio i lawr i waelod yr adran hon i glicio ar y botwm 'Nesaf'.
Mae nifer fawr o ddulliau golygu Python ar gael.
Gwnewch yn siŵr bod gennych chi ganiatâd i wneud hynny cyn gosod meddalwedd newydd. Mae yna opsiynau mewn porwyr hefyd lle nad oes angen caniatâd gweinyddol.
Dyma ein hargymhellion ni:
Golygydd glân a syml sy'n berffaith ar gyfer dechreuwyr llwyr.
Mae angen ei osod o thonny.org.
Amgylchedd codio mwy modern a hyblyg sy'n aml wedi'i osod yn barod ar systemau Microsoft.
Mae ganddo ddewis da o offer ac ychwanegiadau ar gyfer dechreuwyr ac arbenigwyr (ysgrifennwyd y wefan hon yn ei chyfanrwydd gan ddefnyddio'r golygydd VS Code).
Mae modd ei lawrlwytho a'i osod o Visual Studio. Sylwch y bydd angen i chi osod yr estyniad Python hefyd.
Mae fersiwn mewn porwr ar gael ar vscode.dev os nad ydych chi'n gallu ei osod.
Dewis gwyddonwyr data sydd â phrofiad blaenorol o godio a Python.
Mae angen ei osod o spyder-ide.org.
Dewis amgen i Spyder ar gyfer gwyddonwyr data gyda phrofiad blaenorol o Python.
Mae modd ei lawrlwytho a'i osod o jupyter.org neu ddefnyddio fersiwn mewn porwr (fersiwn brawf) o'r un ddolen.
Mae hefyd yn bosib ei ddefnyddio ar-lein fel rhan o Google Collaboration heb ei osod.
Dewiswch yr un sy'n gweddu orau i'ch anghenion a'ch hawliau gosod chi.
Nawr eich bod chi wedi dewis golygydd Python, mae'n amser i ni edrych ar sut i fewnforio data o ffeil CSV i'ch rhaglen.
Y peth cyntaf i'w wneud yw creu ffeil Python newydd a'i harbed yn yr un ffolder â'ch ffeil CSV.
Byddwn yn creu'r rhaglen fesul cam, gan esbonio beth mae pob rhan yn ei wneud a sut i brofi bod popeth yn gweithio.
I gyrraedd y rhaglen lawn heb esboniad, sgroliwch i lawr i Gam 5.
Cam 1: Mewnforio adnoddau/llyfrgelloedd
Mae rhaglenni Python yn aml yn defnyddio adnoddau ychwanegol, o'r enw llyfrgelloedd, i'w helpu i wneud tasgau penodol.
Yn yr achos hwn, mae angen i ni fewnforio (defnyddio) llyfrgell o'r enw 'csv' er mwyn i ni gyrchu'r cod i drin ein ffeil CSV.
Cam 2: Ychwanegu newidynY cam nesaf yw creu newidyn (lle penodol i storio'r data). Byddwn yn enwi'r newidyn hwn yn 'stem_orders' ac yn dweud wrth y rhaglen y bydd y newidyn hwn yn rhestr sy'n defnyddio cromfachau sgwâr gwag.
Cam 3: Cyrchu ein ffeil CSVNawr, rydyn ni'n barod i ddweud wrth ein rhaglen am y ffeil CSV sydd angen ei defnyddio ar gyfer hyn.
Cyn mewnbynnu'r darn nesaf hwn o god, bydd angen i chi wneud yn siŵr bod eich ffeil Python wedi'i harbed yn yr un ffolder â'r ffeil CSV rydych chi eisoes wedi'i chreu.
Bydd angen i chi hefyd wybod yr union enw a roddwyd i'ch ffeil CSV. Ar gyfer yr enghreifftiau hyn, enw'r ffeil oedd 'Stem_Orders.csv'.
Mae'r cod isod yn ychwanegu tair llinell newydd.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
Cilosodiadau: Mae llinellau 6 a 7 wedi'u cilosod oherwydd eu bod yn perthyn i'r bloc 'with' sydd uwch eu pennau. Yn Python, mae cilosod yn dangos pa gyfarwyddiadau sydd wedi'u grwpio gyda'i gilydd.
Y rheol bwysicaf yw defnyddio bylchau yn unig neu dabiau yn unig, ond byth cymysgedd o'r ddau.
Cam 4: Creu'r rhestrNawr bod ein rhaglen wedi agor y ffeil CSV, mae angen iddo ddarllen pob rhes, deall beth mae pob gwerth yn ei gynrychioli, ac ychwanegu'r gwerthoedd hynny at ein rhestr 'stem_orders'.
Byddwn hefyd yn rhoi enw newidyn clir i bob gwerth, fel bod ein rhaglen yn haws i'w darllen a'i deall yn nes ymlaen.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
8
9 for row in reader:
10 order_id = int(row[0])
11 channel = row[1]
12 electronics = int(row[2])
13 robotics = int(row[3])
14 science = int(row[4])
15 stem_orders.append((order_id, channel, electronics, robotics, science))
Dolennau ailadrodd: Mae llinell 9 yn dechrau cylch am. Mae hyn yn dweud wrth Python i fynd drwy'r ffeil CSV un rhes ar y tro. Ar gyfer pob rhes, mae'n adfer y gwerthoedd, yn trosi'r rhai sydd eu hangen fel rhifau, ac yn ychwanegu popeth at ein rhestr. Mae'r ddolen yn ailadrodd nes bod dim rhesi ar ôl.
Trefn Rhestr: Mae Python yn dechrau cyfrif ar 0. Mae hyn yn golygu mai:
Cyfanrif a Llinyn:Pan fydd Python yn darllen data o ffeil CSV, mae'n trin popeth fel llinyn - testun mewn dyfynodau. Ond mae rhai o'n gwerthoedd yn rhifau sydd angen eu defnyddio ar gyfer cyfrifiadu. I droi llinyn yn rhif cyfan, rydyn ni'n defnyddio int(). Dydyn ni ddim yn trosi'r sianel oherwydd ei fod yn cynnwys geiriau ("Online" neu "In_Person"), nid rhifau.
Cam 5: ProfiAr hyn o bryd, dydy'r rhaglen yn dangos dim byd pan fyddwn ni'n ei rhedeg. Mae hynny oherwydd bod popeth y mae wedi'i wneud hyd yma yn digwydd yn y cefndir.
Mae profi yn rhan bwysig o raglennu. Cyn i ni symud ymlaen, rydyn ni eisiau gwirio bod ein rhaglen wedi agor y ffeil yn gywir ac wedi storio'r data yn ein rhestr.
I wirio ein gwaith, rydyn ni'n gallu defnyddio'r gorchymyn 'print()'. Mae hyn yn dweud wrth Python i arddangos rhywbeth yn y gragen neu'r derfynell - yn yr achos hwn, cynnwys ein rhestr 'stem_orders'.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
8
9 for row in reader:
10 order_id = int(row[0])
11 channel = row[1]
12 electronics = int(row[2])
13 robotics = int(row[3])
14 science = int(row[4])
15 stem_orders.append((order_id, channel, electronics, robotics, science))
16
17 print(stem_orders)
Os ydych chi nawr yn clicio ar y gorchymyn 'run' yn eich meddalwedd golygu, dylech weld y data o'r ffeil CSV wedi'i atgynhyrchu yn ffenestr y gragen/ffenestr derfynell eich rhaglen olygu. Dylai edrych fel hyn:
[(201, 'Online', 42, 15, 63), (202, 'InPerson', 58, 22, 41), (203, 'Online', 37, 18, 55),
(204, 'InPerson', 12, 47, 72), (205, 'Online', 29, 33, 88), (206, 'InPerson', 64, 11, 49),
(207, 'Online', 23, 9, 70), (208, 'Online', 51, 27, 46), (209, 'InPerson', 34, 14, 39),
(210, 'InPerson', 19, 31, 77)]
Yn dibynnu ar eich golygydd, bydd yr allbwn yn ymddangos ar un llinell hir neu'n lapio ar draws sawl llinell. Mae'r ddwy ffurf yn normal.
Cam 6: DadfygioAnaml iawn y mae rhaglen yn gweithio'n berffaith ar y cynnig cyntaf, yn enwedig pan fydd y rhaglen yn ddieithr i chi.
Rydyn ni wedi crynhoi'r gwallau cyffredin a allai atal eich cod rhag gweithio gan ddefnyddio'r negeseuon gwall sy'n cael eu creu gan raglen olygu Thonny.
Mae llawer o raglenni golygu Python yn rhoi gwybodaeth ychwanegol fel rhif llinell, awgrym o gystrawen neu'r newidyn sy'n achosi'r broblem er mwyn eich helpu i ddod o hyd i'r gwall.
Mae dadfygio yn rhan arferol o raglennu. Os ydych chi'n dod ar draws gwall, darllenwch y geiriad yn araf - mae'n aml yn dweud wrthych yn union ble i edrych.
Nawr bod eich data wedi'i storio mewn rhestr, gallwch ddolennu drwyddo i gyfrifo cyfansymiau neu ateb cwestiynau. Mae pob rhes yn cynnwys gwerthoedd un archeb, a thrwy ddefnyddio'r safle cywir (mynegai) gallwch ddewis pa golofn rydych chi am weithio arni. Bydd Python wedyn yn gwneud y gwaith adio, cyfrif neu gymharu ar eich rhan.
Cyn i ni ddechrau, mae angen dileu llinell 17 o'r cod - y cyfarwyddyd profi i argraffu'r set ddata gyfan. Mae'n ddiangen bellach - rydyn ni'n gwybod bod y data yno erbyn hyn.
Nodyn atgoffa: Mae pob pennawd yn ein rhestr 'stem_orders' yn edrych fel (rhif archeb, sianel, electroneg, roboteg, gwyddoniaeth), gyda order[0] yn cyfeirio at rhif archeb, order[1] at sianel, order[2] at electroneg, ac yn y blaen...
Cyfanswm y pecynnau electroneg a archebwyd
Sut allwn ni ddefnyddio ein rhaglen i ddarganfod cyfanswm y Pecynnau Electroneg a archebwyd?
Bydd angen creu newidyn newydd i storio'r cyfanswm hwn. I ddechrau, byddwn yn pennu ei werth i 0..
Gallwn wedyn ddefnyddio cylch am i fynd drwy bob rhes o ddata yn ein rhestr, gan ychwanegu'r rhif o'r golofn electroneg at ein newidyn newydd, gan gynhyrchu cyfanswm.
Yn olaf, mae angen argraffu'r newidyn hwnnw er mwyn i ni ei weld a chael llinyn o eiriau o'i flaen, fel ein bod ni'n gwybod beth sy'n cael ei argraffu yn y gragen/terfynell.
17 total_electronics = 0
18
19 for order in stem_orders:
20 total_electronics += order[2]
21
22 print("Total electronics kits:", total_electronics)
Ar gyfer yr enghraifft hon, dewiswyd defnyddio'r gair 'order' yn hytrach na 'row' yn y cylch am, gan fod pob set o ddata o fewn y rhestr 'stem_orders' yn cynrychioli archeb. Mae hefyd yn gwahanu'r defnydd o'r data oddi wrth y broses o fewnforio'r data.
Wrth greu neu newid newidyn, rydyn ni'n defnyddio arwydd hafal. Fodd bynnag, os ydyn ni eisiau ychwanegu at werth/rhestr/llinyn presennol newidyn, rydyn ni'n defnyddio +=, sydd hyn yn haws nag ysgrifennu:
Unwaith y byddwch yn barod, rhedwch y rhaglen a dylech weld y canlynol yn eich ffenestr cragen/terfynell:
>>> %Run stem_orders.py
Total electronics kits: 369
>>>
Cyfanswm nifer y pecynnau roboteg
Gallwn ddefnyddio'r un strwythur gyda newidyn a llinyn gydag enw newydd.
Cofiwch: mae'r pecynnau roboteg mewn colofn wahanol o'r set ddata.
24 total_robotics = 0
25
26 for order in stem_orders:
27 total_robotics += order[3]
28
29 print("Total robotics kits:", total_robotics)
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
>>>
Cymharu nifer yr archebion ar-lein ac archebion wyneb yn wyneb
Er mwyn gallu cymharu nifer yr archebion ar-lein â'r archebion wyneb yn wyneb, mae angen i ni ddysgu sut i wirio am linynnau.
Rydyn ni'n gwybod mai dim ond dau opsiwn sydd i'r data yn y golofn hon: "Online" neu "InPerson". Mae hyn yn golygu ein bod ni'n gallu defnyddio datganiad 'os' gydag opsiwn 'fel arall'
Bydd angen dau newidyn i storio'r cyfansymiau ar gyfer pob un a rhifydd sy'n ychwanegu un at y newidyn perthnasol.
31 online_count = 0
32 inperson_count = 0
33
34 for order in stem_orders:
35 if order[1] == "Online":
36 online_count += 1
37 else:
38 inperson_count += 1
39
40 print("Online orders:", online_count)
41 print("In-person orders:", inperson_count)
Dylai rhedeg y rhaglen hon nawr gynhyrchu'r canlynol yn eich cragen/terfynell.
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
Online orders: 5
In-person orders: 5
>>>
Mae'r datganiad 'os' rydyn ni wedi'i ddefnyddio yma yn gwirio ein data yn erbyn y gair "Online" yn unig, heb ailwirio ei fod yn gorfod bod yn "InPerson" os nad yw'n hynny wir. Er enghraifft, pe bai rhywun wedi camdeipio "Online" fel "online" yn y daenlen wreiddiol, nid yw hyn yn cyd-fynd â'r datganiad 'os' ac felly byddai'n cael ei gyfrif fel archeb wyneb yn wyneb.
Er mwyn sylwi ar enwau sianeli sydd wedi'u mewnbynnu'n anghywir heb ystumio'r cyfrif, gallech ddefnyddio datganiad 'os' gydag adran 'fel arall os' ac adran 'fel arall':
Y nifer uchaf o becynnau gwyddoniaeth mewn un archeb
Yn hytrach na nodi cyfanswm data mewn colofn, byddwn yn ysgrifennu rhaglen sy'n dod o hyd i'r gwerth uchaf yn y golofn honno.
Gan ddefnyddio'r un strwythur cylch am â'r holl enghreifftiau blaenorol ynghyd â datganiad 'os' unigol, gallwn greu darn byr o god i ganfod yr ateb.
43 highest_science = 0
44
45 for order in stem_orders:
46 if order[4] > highest_science:
47 highest_science = order[4]
48
49 print("Highest science order:", highest_science)
Dim ond os yw gwerth yr archebion cyfredol yn uwch na'r gwerth blaenorol y mae'r rhaglen hon yn newid y newidyn 'highest_science'.
Pan fyddwch chi'n rhedeg eich rhaglen nawr, dylai'r neges ar sgrin y gragen/terfynell gynnwys y canlynol:
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
Online orders: 5
In-person orders: 5
Highest science order: 88
>>>
Mae'n bosib bod y gweithgaredd hwn wedi teimlo fel troi rhywbeth cyflym a syml mewn taenlen yn broses llawer mwy cymhleth a llafurus.
Ond mae yna resymau da pam mae dysgu gweithio gyda ffeiliau CSV a Python yn werth chweil:
I grynhoi: er bod yr ymgais gyntaf yn gallu teimlo'n araf neu'n gymhleth, bydd y sgiliau rydych chi'n eu datblygu yma yn eich helpu i weithio'n hyderus gyda setiau data llawer mwy, o ran maint a chymhlethdod, yn y dyfodol.
This activity is your first step into using Python to explore data.
We'll work through everything together: bringing a spreadsheet into your program, understanding how the data is stored, and writing simple code to pull out the information you're interested in. Each example builds gently on the last, helping you grow your confidence as you go.
By working through this activity, you'll learn how to:
Click on the next button to get started.
A Welsh STEM Outreach Team has been running a new programme where schools can order hands-on classroom kits to support science and technology lessons. Each kit focuses on a different area of STEM learning - Electronics, Robotics, and General Science.
Over the past few weeks, schools have been placing orders either online or in person at community events. The team now needs help organising and analysing this information so they can understand demand, plan stock levels, and prepare future deliveries.
You've been given a small sample of recent orders.
Each row in the below table represents one order from one school, showing:
| OrderID | Channel | ElectronicsKits | RoboticsKits | ScienceKits |
|---|---|---|---|---|
| 201 | Online | 42 | 15 | 63 |
| 202 | InPerson | 58 | 22 | 41 |
| 203 | Online | 37 | 18 | 55 |
| 204 | InPerson | 12 | 47 | 72 |
| 205 | Online | 29 | 33 | 88 |
| 206 | InPerson | 64 | 11 | 49 |
| 207 | Online | 23 | 9 | 70 |
| 208 | Online | 51 | 27 | 46 |
| 209 | InPerson | 34 | 14 | 39 |
| 210 | InPerson | 19 | 31 | 77 |
Please Note: As we are planning to use this dataset inside a Python program, all spaces have been removed. As an alternative you could replace them with underscores, for example 'In_Person'.
1. Copy the above table into a spreadsheet.
2. Which order includes the highest number of Robotics Kits?
3. How many Science Kits were ordered in total?
4. How many orders were placed online vs in-person?
A Python program cannot access data in our current spreadsheet. So, we need to change the format into something called a .csv file - which Python can read.
CSV stands for Comma-Separated Values.
Instead of storing data with colours, borders, formulas, or formatting (like Excel does), a CSV stores only the raw text of the table:
That's it. No hidden features. No styling. Just plain text.
Because it's so simple, almost every programming language - including Python - can read CSV files easily
It also reduces the file size substantially from that of a spreadsheet.
Let's return to our spreadsheet, make sure we've removed any additions (such as functions, calculations, or totals), and then select the 'save as' option from the file menu.
Create a folder for this activity's files in a place you'll remember.
In the 'save as type' dropdown menu, select: CSV(comma delimited)
Give your file a name (without spaces), such as stem_orders.csv
Click save.
If you get a warning message warning about the loss of features, this is normal (CSV files only store plain text), choose yes to continue.
If you are curious about how the data in a CSV file differs from that in a spreadsheet, you can open your file using notepad.
We are now going to look at setting up a Pyton program to use our CSV file but first, let us run through some options for software in which to write a Python program.
If you already have an editor, feel free to scroll down to the bottom of this section to click on the next button.
There are a large number of Python editors available.
Please make sure you have permission before installing new software. There are also in-browser options that do not require admin permissions.
Here are our recommendations:
This is a clean, simple editor perfect for complete beginners.
It requires installation from thonny.org.
A more modern, flexible coding environment that is often already installed on Microsoft systems.
Has a good selection of tools and add-ins for beginners through to experts (this whole website was written using the VS Code editor).
Can be downloaded and installed from Visual Studio. Please note that you will also need to install the Python extension.
Has an in-browser version available at vscode.dev if unable to install.
Preferred by data scientists with previous experience of coding and Python.
Requires installation from spyder-ide.org.
An alternative to Spyder for data scientists with previous Python experience.
Can be downloaded and installed from jupyter.org or used in-browser (test version) from the same link.
It is also possible to use online as part of a Google Collaboration without installation.
Please choose the one that best suits your needs and installation permissions.
Now that you've chosen a Python editor, let's look at how to import data from a CSV file into your program
First thing to do is to create a new python file and save it in the same folder as your CSV file.
We'll build the program step by step, explaining what each part does and how to test that everything is working.
For the full program without explanation, please scroll down to step 5.
Step 1: Importing tools/libraries
Python programs often use extra tools, called libraries, to help them do specific jobs.
In this case we need to import (use) a library called 'csv' to provide us with the code to handle our CSV file.
Step 2: Adding a variableWe then need to create a variable (a named place to store the data). We shall call this variable stem_orders and tell the program this variable will be a list using empty square brackets.
Step 3: Accessing our CSVNow we're ready to tell our program about the CSV file it will need to use for this.
Before entering this next snippet of code, you will need to make sure that your Python file is saved in the same folder as the CSV you've already created.
You will also need to know the exact name you gave your CSV file. For these examples the file was called 'Stem_Orders.csv'.
The code below adds three new lines.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
Indentations: Lines 6 and 7 are indented because they belong to the 'with' block above them. In Python, indentation shows which instructions are grouped together.
The most important rule is to use only spaces or only tabs, never a mix.
Step 4: Creating the listNow that our program has opened the CSV file, it needs to read each row, understand what each value represents, and add those values to our 'stem_orders' list.
We shall also give each value a clear variable name, so our program is easier to read and understand later.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
8
9 for row in reader:
10 order_id = int(row[0])
11 channel = row[1]
12 electronics = int(row[2])
13 robotics = int(row[3])
14 science = int(row[4])
15 stem_orders.append((order_id, channel, electronics, robotics, science))
For loops: Line 9 starts a 'for loop'. This tells Python to go through the CSV one row at a time. For each row, it retrieves the values, converts the ones we need as numbers, and adds everything to our list. The loop repeats until there are no rows left.
List Order: Python starts counting at 0. This means:
Integer vs String:When Python reads data from a CSV, it treats everything as a string - text inside quotes. But some of our values are numbers that we want to use for calculations. To turn a string into a whole number, we use int(). We don't convert channel because it contains words ("Online" or "In_Person"), not numbers.
Step 5: TestingAt the moment, our program doesn't show anything when we run it. That's because everything it has done so far happens in the background.
Testing is an important part of programming. Before we move on, we want to check that our program has opened the file correctly and stored the data in our list
To check our work, we can use the 'print()' command. This tells Python to display something in the shell or terminal - in this case, the contents of our 'stem_orders' list.
1 import csv
2
3 stem_orders = []
4
5 with open("Stem_Orders.csv", newline="") as file:
6 reader = csv.reader(file)
7 next(reader)
8
9 for row in reader:
10 order_id = int(row[0])
11 channel = row[1]
12 electronics = int(row[2])
13 robotics = int(row[3])
14 science = int(row[4])
15 stem_orders.append((order_id, channel, electronics, robotics, science))
16
17 print(stem_orders)
If you now click the run command inside your editor you should see the data from our CSV reproduced in the shell/terminal window of your editor. It should look like this:
[(201, 'Online', 42, 15, 63), (202, 'InPerson', 58, 22, 41), (203, 'Online', 37, 18, 55),
(204, 'InPerson', 12, 47, 72), (205, 'Online', 29, 33, 88), (206, 'InPerson', 64, 11, 49),
(207, 'Online', 23, 9, 70), (208, 'Online', 51, 27, 46), (209, 'InPerson', 34, 14, 39),
(210, 'InPerson', 19, 31, 77)]
Depending on your editor, the output may appear on one long line or wrap across several lines. Both are normal.
Step 6: DebuggingIt is very rare for a program to work perfectly on the first try, especially when you're new to it.
We have put together the common errors which may stop your code from working using the error messages produced inside the Thonny editor.
Many Python editors give additional information such as line number, suggested syntax, or the problem variable to help you locate the error.
Debugging is a normal part of programming. If you get an error, read it slowly - it often tells you exactly where to look.
Now that your data is stored in a list, you can loop through it to calculate totals or answer questions. Each row contains the values from one order, and by using the correct position (index) you can choose which column you want to work with. Python will then do the adding, counting, or comparing for you.
Before we start, let us remove line 17 from our code - the testing instruction to print the whole dataset. This is no longer needed - we know the data is there now.
Reminder: Each order in our stem_orders list looks like (order_id, channel, electronics, robotics, science), with order[0] referring to order_id, order[1] being channel, order[2] is electronics, and so on...
Total number of electronic kits ordered
How can we use our program to find out the total number of Electronics Kits ordered?
We will need to create a new variable to store this total in. Initially we shall set its value to 0.
We can then use a for loop to go through each row of data within our list, adding the number from the electronics column to our new variable, producing a total.
Finally, we need to have that variable printed so we can see it and have a string of words in front of it, so we know what is being printed in the shell/terminal.
17 total_electronics = 0
18
19 for order in stem_orders:
20 total_electronics += order[2]
21
22 print("Total electronics kits:", total_electronics)
For this example, we chose to use the word 'order' instead of 'row' in the for loop as each set of data within the stem_orders list represents an order. It also separates our usage of the data from our importing of it.
When creating or changing a variable we use an equals sign. However, if we want to add to a variable's existing value/list/string we use +=, this is easier than writing:
Once ready, run your program and hopefully you should see the following in your shell/terminal window:
>>> %Run stem_orders.py
Total electronics kits: 369
>>>
Total number of robotics kits
We can use the same structure with a renamed variable and string.
Remember: the robotics kits are in a different column of the dataset.
24 total_robotics = 0
25
26 for order in stem_orders:
27 total_robotics += order[3]
28
29 print("Total robotics kits:", total_robotics)
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
>>>
Number of online vs in-person orders
To determine the number of online vs in-person orders we need to learn how to check for strings.
We know that our data only has two options within this column: "Online" or "InPerson". This means we can use an if statement with an else option.
We will need two variables to store the totals for each and have a counter that adds one to the correct variable.
31 online_count = 0
32 inperson_count = 0
33
34 for order in stem_orders:
35 if order[1] == "Online":
36 online_count += 1
37 else:
38 inperson_count += 1
39
40 print("Online orders:", online_count)
41 print("In-person orders:", inperson_count)
Running this program should now produce the following in your shell/terminal.
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
Online orders: 5
In-person orders: 5
>>>
The if-statement we've used here only checks our data against the word "Online", with no double checking that if it's not that, it must be "InPerson". For example, if someone had mistyped "Online" as "online" in the original spreadsheet, this does not match with the if statement and would therefore be counted as an In-person order.
To catch these incorrectly entered channel names without skewing the counts, you could use an if-statement with an else if and an else section:
Highest number of science kits in a single order
Instead of totalling the data in a column, we shall write a program that finds the highest value in it.
Using the same for loop structure as all the previous examples along with a single if-statement, we can produce this short bit of code to reach the answer.
43 highest_science = 0
44
45 for order in stem_orders:
46 if order[4] > highest_science:
47 highest_science = order[4]
48
49 print("Highest science order:", highest_science)
This program only changes the 'highest_science' variable if the current orders value is higher than the previous.
When you run your program now, the resulting shell/terminal screen should contain the following:
>>> %Run stem_orders.py
Total electronics kits: 369
Total robotics kits: 227
Online orders: 5
In-person orders: 5
Highest science order: 88
>>>
This activity might have felt like turning something quick and simple in a spreadsheet into a much more complex and time-consuming process.
However, there are good reasons why learning to work with CSVs and Python is worthwhile:
In short: Although the first attempt may feel slow or complicated, the skills you've developed here will help you work confidently with much bigger and more complex datasets in the future.