0Pricing
Pandas & NumPy Academy · Lesson

Adding and Dropping Columns

Add new computed columns, rename existing ones, and drop unwanted columns or rows with drop().

Adding and Dropping Columns is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)

Using assign() for Method Chaining

df.assign(new_col=expression) returns a new DataFrame with the added column without modifying the original. Unlike direct assignment it fits naturally into a method chain. You can add multiple columns in one call, and later column expressions can reference earlier columns defined in the same assign() call using lambda functions.

import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
result = (df
    .assign(sum_xy=lambda d: d['x'] + d['y'])
    .assign(ratio=lambda d: d['x'] / d['sum_xy'])
)
print(result)

Renaming Columns with rename()

df.rename(columns={'old': 'new'}) returns a new DataFrame with renamed columns. Pass a dict to rename selected columns without affecting others. You can also rename by function: df.rename(columns=str.upper) uppercases all column names. Always rename before merging DataFrames from different sources to ensure key columns align.

import pandas as pd

df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]})
renamed = df.rename(columns={'a': 'alpha', 'b': 'beta'})
print(renamed.columns.tolist())   # ['alpha', 'beta', 'c']

# Rename all columns to uppercase
print(df.rename(columns=str.upper).columns.tolist())  # ['A', 'B', 'C']

Cleaning Column Names

Real-world column names often have spaces, special characters, or inconsistent casing. A common preprocessing step is to normalise them: strip whitespace, convert to lowercase, and replace spaces with underscores. This makes columns accessible via dot notation and avoids quoting issues in SQL-like query strings.

import pandas as pd

df = pd.DataFrame(columns=['First Name', 'Last Name', 'Email Address'])
df.columns = (df.columns
    .str.strip()
    .str.lower()
    .str.replace(' ', '_', regex=False)
)
print(df.columns.tolist())  # ['first_name', 'last_name', 'email_address']

Inserting a Column at a Specific Position

df.insert(loc, column, value) inserts a column at integer position loc, shifting other columns to the right. This is useful when you want the new column to appear next to related columns rather than at the end. It modifies the DataFrame in place, unlike assign().

import pandas as pd

df = pd.DataFrame({'name': ['A', 'B'], 'score': [80, 90]})
df.insert(1, 'grade', ['B', 'A'])
print(df)
#   name grade  score
# 0    A     B     80
# 1    B     A     90

Dropping Columns with drop()

df.drop(columns=['col1', 'col2']) returns a new DataFrame without those columns. The older syntax df.drop(['col1', 'col2'], axis=1) also works but is less readable. To drop in place, pass inplace=True. Always prefer returning a new DataFrame in pipelines to preserve the original for comparison or rollback.

import pandas as pd

df = pd.DataFrame({'a': [1,2], 'b': [3,4], 'c': [5,6], 'd': [7,8]})
cleaned = df.drop(columns=['b', 'd'])
print(cleaned.columns.tolist())  # ['a', 'c']

Dropping Rows with drop()

df.drop(index=['r1', 'r2']) removes rows by label. df.drop([0, 2]) removes rows 0 and 2 from a default integer index. Dropping rows is commonly used to remove known bad records, outliers, or test rows after data cleaning. Prefer boolean indexing for condition-based removal to keep the code readable.

import pandas as pd

df = pd.DataFrame({'x': [10, 20, 30, 40]}, index=['a', 'b', 'c', 'd'])
trimmed = df.drop(index=['b', 'd'])
print(trimmed)
#     x
# a  10
# c  30

pop() to Remove and Return a Column

df.pop('col') removes the column from the DataFrame in place and returns it as a Series. This is useful when you need to extract a target column (label) from a feature matrix — you remove it from the DataFrame and hold it separately for use as the y variable in a model.

import pandas as pd

df = pd.DataFrame({'feature1': [1,2], 'feature2': [3,4], 'target': [0,1]})
y = df.pop('target')   # removes column and returns as Series
X = df                 # remaining features
print(y.tolist())      # [0, 1]
print(X.columns.tolist())  # ['feature1', 'feature2']

Reordering Columns

To reorder columns, select them in the desired order using df[['col3', 'col1', 'col2']]. For large DataFrames where you only want to move a few columns, compute the desired order programmatically: move priority columns to the front and let the rest follow. This is a common reporting step before exporting to Excel.

import pandas as pd

df = pd.DataFrame({'id': [1,2], 'score': [80,90], 'name': ['A','B']})
# Move 'name' and 'id' to front
cols = ['name', 'id'] + [c for c in df.columns if c not in ['name', 'id']]
df = df[cols]
print(df.columns.tolist())  # ['name', 'id', 'score']

Updating Existing Column Values

Updating all values of an existing column uses the same assignment syntax as adding a new one: df['col'] = new_values. Use df.loc[mask, 'col'] = value to update only the rows matching a condition. Never use chained indexing for updates — always use .loc to avoid the SettingWithCopyWarning.

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Carol'], 'score': [45, 80, 92]})
# Set scores below 50 to 50 (floor)
df.loc[df['score'] < 50, 'score'] = 50
print(df['score'].tolist())  # [50, 80, 92]

Quick Check

Test your understanding of adding and dropping columns from this lesson.

Lesson Recap

In this lesson you learned: new columns are added via assignment or the method-chain-friendly assign(), rename() changes column names without altering data, and drop() removes columns or rows and returns a new DataFrame by default. Next up we use head(), tail(), info(), and describe() to quickly profile any DataFrame.

Frequently asked questions

Is the “Adding and Dropping Columns” lesson free?

Yes — the full text of “Adding and Dropping Columns” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Adding and Dropping Columns”?

Add new computed columns, rename existing ones, and drop unwanted columns or rows with drop(). You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Adding and Dropping Columns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating DataFrames
  2. Selecting Columns and Rows
  3. Adding and Dropping Columns
  4. Basic DataFrame Inspection
← Back to Pandas & NumPy Academy