Selecting Columns
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 35 of 60.
Most questions are about one column: the average weight, the tallest dog. Put the column's name in square brackets to pick it out:
dogs = pd.DataFrame({
"name": ["Max", "Luna", "Bo", "Kira"],
"kg": [30, 8, 22, 12],
"cm": [61, 30, 55, 40],
})
print(dogs["kg"])
print(dogs["kg"].mean())This prints a Series, named after its column, then the average weight:
0 30
1 8
2 22
3 12
Name: kg, dtype: int64
18.0For several columns, put a list of names inside the brackets. You get a smaller DataFrame, its columns in your order:
print(dogs[["name", "cm"]])This prints:
name cm
0 Max 61
1 Luna 30
2 Bo 55
3 Kira 40Picking columns is how a model later gets exactly the features it should learn from.
Challenge
MediumA review site loads phones.csv into phones, with the columns model, price, battery_h (hours) and weight_g. The program reads one column name into column.
- Print the first 3 rows of a table with only
modeland that column. - Print its smallest and largest value and its mean, rounded to 1 decimal, as below.
For a table of watches and the column strap_mm:
model strap_mm
0 Orca 20
1 Quartzy 18
2 Brio 22
strap_mm: from 16 to 24, average 20.4Try it yourself
import pandas as pd
phones = pd.read_csv("phones.csv")
column = input()
# 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
7pandas DataFrames
SeriesDataFramesReading CSV FilesInspecting DataSelecting ColumnsRecap: Movie Ratings2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler