Menu
CoddyTech

New Columns

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 40 of 60.

A table often lacks the number you need: it has distance and time, but no speed. Column math works row by row, like array math, with no loop:

The rides table drawn as a grid with the columns rider, km and hours, and a new highlighted column speed on the right holding 21.0, 20.0 and 22.0, each row worked out as its km divided by its hours

rides = pd.DataFrame({
    "rider": ["Ana", "Ben", "Cleo"],
    "km": [42, 30, 66],
    "hours": [2, 1.5, 3],
})
rides["speed"] = rides["km"] / rides["hours"]
print(rides)

Assigning to a new name adds the column on the right:

  rider  km  hours  speed
0   Ana  42    2.0   21.0
1   Ben  30    1.5   20.0
2  Cleo  66    3.0   22.0

A number works too: rides["hours"] * 60 gives minutes. Assigning to a name that exists replaces that column.

A model often learns more from a ratio like speed than from the two raw numbers it came from.

challenge icon

Challenge

Medium

A stationery shop keeps its stock in stock.csv, loaded into stock, with the columns product, price (per item) and quantity (items on the shelf).

  1. Add a column value: each product's price times its quantity.
  2. Print stock.
  3. Print the total value of the shelf, as below.

For a shop with two products:

  product  price  quantity  value
0    tape    1.5        10   15.0
1    clip    0.5        30   15.0
Total value: 30.0

Try it yourself

import pandas as pd

stock = pd.read_csv("stock.csv")

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler