Menu
CoddyTech

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:

The dogs table drawn as a grid with the columns name, kg and cm; the kg column is highlighted and labelled dogs kg, a Series, while the other columns fade

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.0

For 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  40

Picking columns is how a model later gets exactly the features it should learn from.

challenge icon

Challenge

Medium

A 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.

  1. Print the first 3 rows of a table with only model and that column.
  2. 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.4

Try it yourself

import pandas as pd

phones = pd.read_csv("phones.csv")
column = input()

# 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