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
- A single column name gives a Series; double brackets keep a frame.
select_dtypespicks columns by type.dropremoves by name, along the column axis.
Keywords and builtins used here
asprinttype
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.
Step 1 of 4 in Selecting rows, step 5 of 26 in pandas.