Skip to main content
Albero Academy

Adding & Dropping

Create derived columns, drop columns and rows, and chain with assign.

Selecting & Filtering8 min

Shaping a table means adding derived columns and removing what you don't need. Pandas does both cleanly, and assign lets you add columns inside a method chain.

Adding columns

assignment and assign()
df["tier"] = df["package"].apply(lambda p: "high" if p >= 8 else "std")
# assign() adds columns and returns a new frame — chainable
df = df.assign(
bonus=df["package"] * 0.1,
total=lambda d: d["package"] + d["bonus"], # can reference just-made cols
)

Dropping

remove rows or columns
df.drop(columns=["bonus", "tier"]) # drop columns
df.drop(index=[0, 1]) # drop rows by label
df.drop_duplicates() # remove duplicate rows

Key takeaways

  1. 01Add columns by assignment, or with assign() inside a method chain.
  2. 02assign can reference columns created earlier in the same call via a lambda.
  3. 03drop(columns=[...]) removes columns; drop(index=[...]) removes rows.
  4. 04drop_duplicates() removes repeated rows.

Finished this chapter?

Mark it complete to track your progress through Pandas.