TExcelTAD
Home › pandas › Adding and Dropping Columns

Adding and Dropping Columns

Most analyses reshape the column set: you add calculated columns, rename confusing ones, drop the ones you don't need and reorder the rest. This lesson collects the tools for all of it, using a small table of team members' working hours.

Adding a column by assignment

Assigning to a new name creates a column. The value can be a constant, a list of the right length, or (most often) a calculation on other columns:

python · try it yourself
import pandas as pd

hours = pd.DataFrame({
    "name": ["Iris", "Omar", "Pia", "Quinn"],
    "billable": [32, 28, 36, 20],
    "internal": [6, 10, 4, 18],
})
hours["total"] = hours["billable"] + hours["internal"]
hours["utilisation"] = (hours["billable"] / hours["total"]).round(2)
hours["team"] = "Design"
print(hours)
    name  billable  internal  total  utilisation    team
0   Iris        32         6     38         0.84  Design
1   Omar        28        10     38         0.74  Design
2    Pia        36         4     40         0.90  Design
3  Quinn        20        18     38         0.53  Design

assign(): add columns without changing the original

assign() returns a new DataFrame with the extra columns. It's handy in method chains, and a lambda lets a new column use columns created earlier in the same call:

python · try it yourself
import pandas as pd

hours = pd.DataFrame({
    "name": ["Iris", "Omar", "Pia", "Quinn"],
    "billable": [32, 28, 36, 20],
    "internal": [6, 10, 4, 18],
})
report = hours.assign(
    total=lambda d: d["billable"] + d["internal"],
    overtime=lambda d: (d["total"] - 37.5).clip(lower=0),
)
print(report)
print(list(hours.columns))   # the original is unchanged
    name  billable  internal  total  overtime
0   Iris        32         6     38       0.5
1   Omar        28        10     38       0.5
2    Pia        36         4     40       2.5
3  Quinn        20        18     38       0.5
['name', 'billable', 'internal']

Conditional columns

np.where(condition, if_true, if_false) picks between two values row by row. For more than two outcomes, np.select takes a list of conditions and a matching list of choices:

python · try it yourself
import numpy as np
import pandas as pd

hours = pd.DataFrame({
    "name": ["Iris", "Omar", "Pia", "Quinn"],
    "billable": [32, 28, 36, 20],
})
hours["target_met"] = np.where(hours["billable"] >= 30, "yes", "no")
hours["band"] = np.select(
    [hours["billable"] >= 35, hours["billable"] >= 25],
    ["high", "medium"],
    default="low",
)
print(hours)
    name  billable target_met    band
0   Iris        32        yes  medium
1   Omar        28         no  medium
2    Pia        36        yes    high
3  Quinn        20         no     low

insert(): add at a specific position

New columns go to the end. insert(position, name, values) places one where you want it (and modifies the frame in place):

python · try it yourself
import pandas as pd

hours = pd.DataFrame({
    "name": ["Iris", "Omar", "Pia"],
    "billable": [32, 28, 36],
})
hours.insert(0, "emp_id", [101, 102, 103])
print(hours)
   emp_id  name  billable
0     101  Iris        32
1     102  Omar        28
2     103   Pia        36

Renaming columns

rename() takes a dictionary of {old: new} names. To transform every name at once, pass a function, or assign a new list to df.columns:

python · try it yourself
import pandas as pd

raw = pd.DataFrame({"Emp Name": ["Iris"], "Billable Hrs": [32], "Internal Hrs": [6]})

print(raw.rename(columns={"Emp Name": "name"}))
clean = raw.rename(columns=lambda c: c.lower().replace(" ", "_"))
print(list(clean.columns))
   name  Billable Hrs  Internal Hrs
0  Iris            32             6
['emp_name', 'billable_hrs', 'internal_hrs']

Dropping columns

drop(columns=[...]) returns a frame without the listed columns. To keep only some columns, it's often clearer to select them instead:

python · try it yourself
import pandas as pd

hours = pd.DataFrame({
    "name": ["Iris", "Omar"],
    "billable": [32, 28],
    "internal": [6, 10],
    "notes": ["", "on leave Fri"],
})
print(hours.drop(columns=["notes"]))
print(hours.drop(columns=["notes", "internal"]).columns.to_list())
print(hours[["name", "billable"]])        # keep instead of drop

removed = hours.pop("notes")              # remove AND return the column
print(removed.to_list(), hours.columns.to_list())
   name  billable  internal
0  Iris        32         6
1  Omar        28        10
['name', 'billable']
   name  billable
0  Iris        32
1  Omar        28
['', 'on leave Fri'] ['name', 'billable', 'internal']

Tip: Dropping a name that doesn't exist raises a KeyError. Pass errors="ignore" if the column may or may not be there.

Reordering columns

Select the columns in the order you want:

python · try it yourself
import pandas as pd

hours = pd.DataFrame({
    "billable": [32, 28],
    "name": ["Iris", "Omar"],
    "internal": [6, 10],
})
print(hours[["name", "internal", "billable"]])
print(hours[sorted(hours.columns)].columns.to_list())
   name  internal  billable
0  Iris         6        32
1  Omar        10        28
['billable', 'internal', 'name']

Test yourself

What does df.assign(total=lambda d: d.a + d.b) do to df?

  1. Adds a total column to df in place
  2. Returns a new DataFrame with a total column; df is unchanged
  3. Renames column a to total
  4. Raises an error because lambdas are not allowed

Which call removes the column tmp?

  1. df.drop("tmp")
  2. df.drop(columns=["tmp"])
  3. df.remove("tmp")
  4. df.delete(columns="tmp")

Which tool creates a column with "pass" where score >= 50 and "fail" otherwise?

  1. np.where(df["score"] >= 50, "pass", "fail")
  2. df.if(score >= 50)
  3. df["score"].replace(50, "pass")
  4. df.rename("pass")