CodeBlanks Logo Icon CodeBlanks

Loading data

Load and inspect a dataset with pandas.

Project: weather readings

In this project you'll process five days of temperature and humidity readings step by step: load, clean, compute statistics, write a report. The data is CSV text and some cells are empty:

gun,sicaklik,nem
1,20,40
2,22,
3,,60
4,26,50
5,24,45

In real projects data comes from a file; here we'll read the text like a file with io.StringIO.

np.genfromtxt

np.genfromtxt turns a text table into a numeric array and makes empty cells nan:

veri = np.genfromtxt(io.StringIO(csv), delimiter=",", skip_header=1)
print(veri.shape)              # (5, 3)
print(np.isnan(veri).sum())    # number of empty cells

skip_header=1 skips the header line; if it isn't skipped, the header is also read as a row of nan.

Practice Load the data

Read the csv text with np.genfromtxt (delimiter=",", skip_header=1). Print the array's shape and the number of empty cells on separate lines.

Starter code

model.py
import io
import numpy as np

csv = "gun,sicaklik,nem\n1,20,40\n2,22,\n3,,60\n4,26,50\n5,24,45\n"

# buraya yaz

Sample solution

model.py
import io
import numpy as np

csv = "gun,sicaklik,nem\n1,20,40\n2,22,\n3,,60\n4,26,50\n5,24,45\n"

veri = np.genfromtxt(io.StringIO(csv), delimiter=",", skip_header=1)
print(veri.shape)
print(np.isnan(veri).sum())

Expected output

(5, 3)
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many data rows does this CSV have (excluding the header)?

  • 5 Correct answer
  • 6
  • 3
  • 4

Explanation: The first line holds the column names; below it are the readings of five days.

2 Read while skipping the header line.

Question
veri = np.genfromtxt(io.StringIO(csv), delimiter=",", ____=1)
Answer
veri = np.genfromtxt(io.StringIO(csv), delimiter=",", skip_header=1)

Explanation: skip_header is the number of lines to skip at the start.

3 Match the pieces.

Term Meaning
io.StringIO Reads text like a file
delimiter="," Separator character
skip_header=1 Skips the header
np.isnan Finds empty cells

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation