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:
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.0A 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
MediumA stationery shop keeps its stock in stock.csv, loaded into stock, with the columns product, price (per item) and quantity (items on the shelf).
- Add a column
value: each product's price times its quantity. - Print
stock. - 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.0Try it yourself
import pandas as pd
stock = pd.read_csv("stock.csv")
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler