Adding and Dropping Columns
A new column is an assignment, and drop returns a new table by default.
A derived column
Assigning to a name that does not exist creates it. The right-hand side is an ordinary column expression, so it lines up row by row.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0]})
df["with_tax"] = df["price"] * 1.08
print(df)
Dropping returns a copy
drop hands back a new table and leaves yours alone unless you reassign. This surprises people who expect it to act in place.
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2]})
smaller = df.drop(columns=["b"])
print(list(smaller.columns))
print(list(df.columns))
Exercise
Try It YourselfWrite add_total(df) that returns a new table with a total column equal to price times quantity, leaving the table it was given unchanged.
Press Run to see output