CodeBlanks Logo Icon CodeBlanks

Viewing first rows

The head() method returns the first n rows of a DataFrame; default n=5.

head, tail, info

When you open a new dataset, the first thing is to look at it:

df.head()        # first 5 rows
df.head(2)       # first 2 rows
df.tail(3)       # last 3 rows
df.info()        # column types and non-null counts

info() immediately shows missing values and columns read with the wrong type (for example text instead of numbers).

describe and value_counts

A summary of numeric columns is taken with describe(), the distribution of categorical columns with value_counts():

df.describe()                 # count, mean, std, min, quartiles, max
df["sehir"].value_counts()    # how often each value appears
df["yas"].nunique()           # number of distinct values

In classification problems, applying value_counts() to the label column shows whether the classes are balanced.

Practice Get to know the data

Find how often each city appears in the sehir column with value_counts() and print the count of the most frequent city. Then print the length of the first 2 rows with len(df.head(2)).

Starter code

model.py
import pandas as pd

df = pd.DataFrame({"sehir": ["Ankara", "İzmir", "Ankara", "Bursa", "Ankara"]})

# buraya yaz

Sample solution

model.py
import pandas as pd

df = pd.DataFrame({"sehir": ["Ankara", "İzmir", "Ankara", "Bursa", "Ankara"]})

sayim = df["sehir"].value_counts()
print(sayim.max())
print(len(df.head(2)))

Expected output

3
2

Questions and answers

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

1 How many rows does <code>df.head()</code> show without an argument?

  • All
  • 5 Correct answer
  • 10
  • 1

Explanation: The default value of n is 5.

2 Show the last 3 rows.

Question
print(df.____(3))
Answer
print(df.tail(3))

Explanation: tail(n) returns the last n rows.

3 Match the methods.

Term Meaning
head() First rows
info() Column types
describe() Numeric summary
value_counts() Value frequencies

All lessons in Beginner

13 Project: Classification

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