Mada za sehemu hiiCreating basic programsMada 3
- Performing exploration of basic programming constructs
- Implementing handling of user inputs and outputs
- Using basic libraries for data science
Using Basic Libraries for Data Science
When we work with data in programming, writing every function from scratch would take a very long time. Python libraries are collections of pre-written code that help us perform common tasks quickly. For data science, three important Python libraries are NumPy, pandas, and matplotlib. These libraries simplify tasks like working with numbers, organizing data in tables, and drawing graphs.
NumPy stands for Numerical Python. It helps us work with groups of numbers called arrays. An array is like a list, but it lets us perform math operations on many numbers at once.
Why use NumPy?
- Fast calculations on large sets of numbers
- Simple syntax for mathematical operations
- Used as the foundation for other data science libraries
Creating a NumPy Array
First, we must import the library:
import numpy as np
Then we can create an array from a list of values. For example, imagine tracking the prices of rice (in Tanzanian shillings) at different markets in Dar es Salaam over one week:
prices = np.array([12000, 12500, 11800, 13000, 12800, 12200, 11900])
print(prices)
This outputs: [12000 12500 11800 13000 12800 12200 11900]
Simple Calculations with NumPy
NumPy makes it easy to calculate totals and averages:
total = np.sum(prices)
average = np.mean(prices)
highest = np.max(prices)
lowest = np.min(prices)
print("Total sales:", total, "TZS")
print("Average price:", average, "TZS")
print("Highest price:", highest, "TZS")
print("Lowest price:", lowest, "TZS")
These single lines replace the need to write loops that add up numbers one by one.
pandas is built on NumPy and provides a way to organize data in DataFrames — tables with rows and columns, similar to a spreadsheet. Each column can hold a different type of data.
Why use pandas?
- Easy to read and write data from files like CSV
- Simple commands to filter, sort, and calculate statistics
- Handles missing data gracefully
Creating a Simple DataFrame
Suppose a small shop in Mwanza tracks sales of three items over three days:
import pandas as pd
data = {
"Item": ["Sugar", "Rice", "Salt"],
"Monday": [5000, 15000, 2000],
"Tuesday": [5500, 14500, 1800],
"Wednesday": [4800, 16000, 2100]
}
df = pd.DataFrame(data)
print(df)
Output:
Item Monday Tuesday Wednesday
0 Sugar 5000 5500 4800
1 Rice 15000 14500 16000
2 Salt 2000 1800 2100
Basic Operations
We can calculate the total sales for each item across the three days:
df["Total"] = df["Monday"] + df["Tuesday"] + df["Wednesday"]
print(df)
We can also find the average sales per day:
daily_totals = df[["Monday", "Tuesday", "Wednesday"]].mean()
print("Average sales per day:", daily_totals)
These operations are much shorter than writing loops to process the data manually.
matplotlib is a library for creating visualizations like line graphs, bar charts, and pie charts. Seeing data as a picture helps us understand trends quickly.
Why use matplotlib?
- Creates clear, professional-looking graphs
- Customizable colors, labels, and titles
- Works well with NumPy and pandas
Drawing a Simple Line Graph
Imagine we record the daily temperature (°C) in Dodoma for one week:
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
temperatures = [28, 30, 32, 31, 29, 27, 28]
plt.plot(days, temperatures)
plt.title("Weekly Temperature in Dodoma")
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.show()
The plt.plot() function draws a line graph. The other functions add a title and labels to make the graph easy to understand.
Drawing a Bar Chart
We can also compare quantities using a bar chart. For example, the number of customers at a café in Arusha over four days:
days = ["Thursday", "Friday", "Saturday", "Sunday"]
customers = [45, 62, 88, 70]
plt.bar(days, customers, color="green")
plt.title("Customer Count at Café Arusha")
plt.xlabel("Day")
plt.ylabel("Number of Customers")
plt.show()
The plt.bar() function creates a bar chart with the given data.
In real data science projects, these three libraries are often used together:
- NumPy creates and processes numerical arrays
- pandas reads, organizes, and cleans data using DataFrames
- matplotlib visualizes the results as graphs
For example, a farmer in Morogoro could use pandas to read a CSV file of monthly rainfall data, use NumPy to calculate the average rainfall, and then use matplotlib to draw a graph showing which months have the most rain. This helps the farmer decide when to plant crops.
- NumPy provides fast numerical operations on arrays of numbers
- pandas organizes data into tables called DataFrames for easy analysis
- matplotlib creates visual graphs to help us see patterns in data
- Together, these libraries make data science tasks much simpler and faster
A shopkeeper in Dar es Salaam can use these libraries to manage their business: pandas to record daily sales of items like cooking oil, rice, and sugar in a table; NumPy to quickly calculate total revenue and average daily sales; and matplotlib to draw a graph showing which days of the week are busiest. This helps the shopkeeper understand sales patterns and plan better, such as ordering more stock before the busiest days.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
- Install and import relevant libraries for data analysis.
- Use Python libraries to manipulate and analyze small datasets.
Tathmini ya matokeo
A Python program using libraries to load, process, and visualize basic data.
Tathmini ya maarifa
Detailed knowledge of:
Method used: The student should explain how to:
- explore different data analysis libraries
Principles: The student should explain the principles of:
- modular programming using libraries.
Theories: The student should explain:
- Common examples of Python libraries
- Concept of data manipulation and visualization.
Circumstantial knowledge:
Detailed knowledge about:
- Data science libraries
Swali
What does NumPy stand for?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado