typestar

Selecting columns in Python

One column is a Series, a list of columns is a DataFrame.

import pandas as pd

frame = pd.DataFrame({
    "lang": ["python", "rust"],
    "tours": [11, 12],
    "tpm": [104.5, 98.0],
})

print(type(frame["lang"]).__name__)
print(frame[["lang", "tpm"]])
print(frame.select_dtypes("number").columns.tolist())
print(frame.drop(columns=["tours"]).columns.tolist())

How it works

  1. A single column name gives a Series; double brackets keep a frame.
  2. select_dtypes picks columns by type.
  3. drop removes by name, along the column axis.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
290
Tokens
114
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 1 of 4 in Selecting rows, step 5 of 26 in pandas.

← Previous Next →