Select columns with bracket notation. One column returns a Series; a list of columns returns a DataFrame. Use df.filter or df.loc for advanced patterns.
Basic selection
import pandas as pd
df = pd.DataFrame({'a': [1,2], 'b': [3,4], 'c': [5,6]})
s = df['a'] # Series
sub = df[['a', 'c']] # DataFrame
print(type(s), type(sub))
Adding and renaming
df['new_col'] = values— add or overwrite columndf.rename(columns={'old': 'new'})— rename (returns copy by default)df.drop(columns=['x'])— remove columnsdf.assign(total=lambda d: d['a'] + d['b'])— functional style
Pitfalls
Chained assignment (df[mask]['col'] = val) can fail silently—prefer df.loc[mask, 'col'] = val. Dot notation (df.col) only works for valid Python identifiers.
Important interview questions and answers
- Q: df['a'] vs df[['a']]?
A: Single brackets → Series; double brackets → DataFrame with one column. - Q: Chained assignment?
A: Setting on a slice may not modify original—use loc with row and column together.
Self-check
- Select two columns into a new DataFrame.
- How do you add a computed column?
Pitfall: Chained assignment df[mask]['col']=x triggers SettingWithCopyWarning—use loc.
Interview prep
- Single vs double brackets?
df['a'] → Series; df[['a']] → DataFrame.
- assign?
Functional column add returning new DataFrame—supports method chaining.