DataFrame Basics
Select Column
Extract one column from a list of row-records by looping and appending each
record's field to a collector list. With pandas, df['col'] performs the same
extraction in one step and returns a Series — a typed, indexed 1D view of that
column rather than a raw list.
By hand
With pandas
df['score'] selects the column by name and returns it as a Series. The
snapshot shows the Series index, values, dtype, and the column name stored on
the Series itself.
naive.py
# trace: ignore records
records = [
{'name': 'al', 'age': 20, 'score': 80},
{'name': 'bo', 'age': 25, 'score': 90},
{'name': 'cy', 'age': 22, 'score': 70},
{'name': 'di', 'age': 28, 'score': 85},
]
col = []
for r in records:
col.append(r['score'])
print('RESULT:', col)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
records = [
{'name': 'al', 'age': 20, 'score': 80},
{'name': 'bo', 'age': 25, 'score': 90},
{'name': 'cy', 'age': 22, 'score': 70},
{'name': 'di', 'age': 28, 'score': 85},
]
df = pd.DataFrame(records)
col = df['score']
print('index:', col.index.tolist())
print('values:', col.tolist())
print('dtype:', col.dtype)
print('name:', col.name)
print('RESULT:', col.tolist())
index: [0, 1, 2, 3]
values: [80, 90, 70, 85]
dtype: int64
name: score
RESULT: [80, 90, 70, 85]
Implementation notes
df['col']returns a Series — the column retains the DataFrame's index and a.nameattribute equal to the column label.df[['col']](double brackets) returns a single-column DataFrame instead. The distinction matters when passing the result to functions that expect a 2D structure.- The returned Series shares data with the DataFrame by default (no copy). Use
.copy()if you need an independent column to modify without affecting the original DataFrame. - To select multiple columns at once, pass a list:
df[['age', 'score']]returns a DataFrame with just those two columns.