Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Your first DataFrames

By the end of this chapter, you'll be able to

  • Create a DataFrame and read a CSV file with pandas
  • Inspect a table: dimensions, column types, first rows
  • Select columns and compute statistics
  • Create a computed column without writing a loop

The DataFrame, a programmable table

pandas handles two structures:

  • a Series: one column of values, with an index (the row labels);
  • a DataFrame: a table of several columns sharing the same index, like a spreadsheet.
import pandas as pd

sales = pd.DataFrame({
    "product": ["millet", "groundnut", "cowpea", "millet", "mango"],
    "region": ["Kaolack", "Kaolack", "Thiès", "Thiès", "Ziguinchor"],
    "kg": [120, 80, 45, 200, 150],
    "price_kg": [300, 650, 500, 300, 250],
})
print(sales)
print(sales.shape)
     product      region   kg  price_kg
0     millet     Kaolack  120       300
1  groundnut     Kaolack   80       650
2     cowpea       Thiès   45       500
3     millet       Thiès  200       300
4      mango  Ziguinchor  150       250
(5, 4)

We build the table from a dictionary: each key becomes a column. On the left, pandas shows the index, numbered from 0. shape gives the dimensions: (rows, columns). Prices are in CFA francs.

Read a CSV file

In real life, data arrives in a file, very often in CSV format: one line per record, values separated by commas or semicolons. pd.read_csv("sales.csv") reads a file. Here, so that the example works everywhere, the file's text is in the code, and io.StringIO makes it look like a file:

import io
import pandas as pd

csv = """date,product,region,kg,price_kg
2026-03-02,millet,Kaolack,120,300
2026-03-02,groundnut,Kaolack,80,650
2026-03-03,cowpea,Thiès,45,500
2026-03-04,millet,Thiès,200,300
2026-03-05,mango,Ziguinchor,150,250
2026-03-05,groundnut,Thiès,60,640
"""
sales = pd.read_csv(io.StringIO(csv))
print(sales.head(3))
print(sales.dtypes)
         date    product   region   kg  price_kg
0  2026-03-02     millet  Kaolack  120       300
1  2026-03-02  groundnut  Kaolack   80       650
2  2026-03-03     cowpea    Thiès   45       500
date        object
product     object
region      object
kg           int64
price_kg     int64
dtype: object

head(3) shows the first 3 rows: the first reflex with a new file. dtypes gives the type of each column: int64 for integers, object for text. Always check the types: a column of numbers read as text distorts every calculation.

Statistics summarise a column into one value.

Step 5 of 5
Text description of the animation
  1. The file is just text: one line per sale, commas between the values.
  2. read_csv splits each line and guesses the type of each column.
  3. We get a DataFrame of 6 rows and 5 columns.
  4. An operation between two columns applies to every row at once.
  5. Statistics summarise a column into one value.

Select and summarise

A column is obtained with square brackets, like a dictionary key. A list of names selects several columns:

import io
import pandas as pd

csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\n"
sales = pd.read_csv(io.StringIO(csv))

print(sales["kg"].sum(), sales["kg"].mean(), sales["kg"].max())
print(sales[["product", "kg"]])
print(sales["kg"].describe())
595 119.0 200
     product   kg
0     millet  120
1  groundnut   80
2     cowpea   45
3     millet  200
4      mango  150
count      5.000000
mean     119.000000
std       60.249481
min       45.000000
25%       80.000000
50%      120.000000
75%      150.000000
max      200.000000
Name: kg, dtype: float64

describe() gives at once the number of values (count), the mean (mean), the standard deviation (std, the spread around the mean), the minimum, the quartiles (25%, 50% = the median, 75%) and the maximum.

Compute a new column

An operation between columns applies to every row at once, without a loop: pandas is said to be vectorised. It is shorter to write and much faster on large volumes.

import io
import pandas as pd

csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\n"
sales = pd.read_csv(io.StringIO(csv))

sales["amount"] = sales["kg"] * sales["price_kg"]
print(sales)
print("Turnover:", sales["amount"].sum(), "FCFA")
     product      region   kg  price_kg  amount
0     millet     Kaolack  120       300   36000
1  groundnut     Kaolack   80       650   52000
2     cowpea       Thiès   45       500   22500
3     millet       Thiès  200       300   60000
4      mango  Ziguinchor  150       250   37500
Turnover: 208000 FCFA

Mini-lab: explore the salesPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

The first run downloads pandas into your browser (a few megabytes, only once).

Your turn

Worked exercise

Worked exercise: the biggest sale

From the sales below, add the amount column, then display the average amount per sale (rounded to the nearest integer) and the row of the sale with the biggest amount.

csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\n"
Hint 1
round(value) rounds to the nearest integer.
Hint 2
sales["amount"].idxmax() gives the index of the row with the biggest amount, and sales.loc[index] displays that row.
Show the solution and common mistakes
import io
import pandas as pd

csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\n"
sales = pd.read_csv(io.StringIO(csv))
sales["amount"] = sales["kg"] * sales["price_kg"]

print("Average amount:", round(sales["amount"].mean()))
print(sales.loc[sales["amount"].idxmax()])
Average amount: 41600
product     millet
region       Thiès
kg             200
price_kg       300
amount       60000
Name: 3, dtype: object

A single row is displayed as a Series: the column names become the index. Name: 3 reminds you of the row's index in the DataFrame.

Common mistakes:

  • Using max() instead of idxmax(): you get the highest amount, but not the row that goes with it.
  • Writing a for loop to compute amount row by row: it works, but it is longer and much slower than an operation between columns.

Summary

  1. 1A DataFrame is a table of typed columns sharing an index; a single column is a Series.
  2. 2pd.read_csv reads a CSV file; head() and dtypes are the first reflexes to inspect it.
  3. 3sales["kg"] selects a column; sum, mean, max and describe summarise it.
  4. 4Operations between columns apply to every row at once, without a loop.
  5. 5A numeric column read as text (dtype object) distorts calculations: always check the types.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.