Adding and Dropping Columns
Add new computed columns, rename existing ones, and drop unwanted columns or rows with drop().
Adding a New Column via Assignment
The simplest way to add a column is direct assignment: df['new_col'] = values. The right-hand side can be a scalar (broadcasts to all rows), a list of the same length, a NumPy array, a Pandas Series (aligned by index), or a computed expression involving existing columns. New columns are added to the right of the DataFrame.
import pandas as pd
df = pd.DataFrame({'price': [10.0, 20.0, 15.0], 'qty': [3, 5, 2]})
df['revenue'] = df['price'] * df['qty']
df['currency'] = 'USD'
print(df)Feature Engineering: Computed Columns
One of the most common DataFrame operations is creating derived features from existing columns. You can compute running totals, ratios, flags, or encode categorical values in a single vectorized expression. These computed columns update automatically when the source columns change if you recompute them, making feature engineering pipelines easy to reproduce.
import pandas as pd
df = pd.DataFrame({'salary': [50000, 80000, 60000],
'bonus': [5000, 12000, 7000]})
df['total_comp'] = df['salary'] + df['bonus']
df['bonus_pct'] = (df['bonus'] / df['salary'] * 100).round(1)
print(df)All lessons in this course
- Creating DataFrames
- Selecting Columns and Rows
- Adding and Dropping Columns
- Basic DataFrame Inspection