3 min read
Data is simply recorded facts: names, marks, prices, dates, temperatures. When facts are organised into rows and columns they form a table. Each row is one record, such as one student. Each column is one kind of fact, such as marks.
You already know tables: an Excel sheet, a school mark list, a bank statement. The first row usually holds column names (the header) and the rest are records.
Python alone can hold a table using lists, but it has no real idea of rows, columns or names. If you want the average of the marks column you must write a loop yourself. Pandas gives Python a proper idea of tables.
header = ["name", "marks"]
rows = [["Asha", 80], ["Ravi", 90], ["Meena", 75]]
print(header)
for row in rows:
print(row)
total = 0
for row in rows:
total = total + row[1]
print("Average:", round(total / len(rows), 2))
Code explained:
| Code | What it does |
|---|---|
| header = [...] | A list holding the column names |
| rows = [[...], ...] | A list of lists; each inner list is one record |
| for row in rows | Repeats for every record |
| row[1] | The second item (marks) of that record |
| total / len(rows) | Total divided by number of records gives the average |
Output explained:
| Output | Meaning |
|---|---|
| First line | The header |
| Next three lines | One record each |
| Average: 81.67 | (80 + 90 + 75) / 3 |
Watch out: This works, but notice how much code a simple average needed and that we had to remember that marks is position 1. Pandas removes this pain.
Quick check: In a table, what is a row and what is a column?
Answer: A row is one record; a column is one kind of fact for all records.
💬 Comments & Discussion
No comments yet
Be the first to share your thoughts!