How to edit a DataFrame column with Pandas

1 min

Knowing how to edit a DataFrame column is one of the core method you will need to know in order to master Pandas and Data manipulation.

Let's take an example DataFrame :

import pandas as pd
import numpy as np
df = pd.DataFrame({"col1": range(0,10)})

Mathematical Operations

Mathematical operations are one the things you will do the most in Python. Especially with the Pandas library.

Here is the way to perform mathematical operations to Pandas Series or DataFrame columns.

# We add 2 to col1 and assign the value to col3
df["col2"] = df["col1"] + 2
print(df["col2"])

# We divide the col3 by 2 and assign the value to col4
df["col3"] = df["col2"] / 2
print(df["col2"])
How to perform mathematical operations on columns

The apply method

Using the lambda function

Sometimes you will need a little bit more than simple mathematical operations.

For example have a logic that extract a specific text from a string.

You can achieve that with DataFrame.apply() method.

You can either provide a method or create a lambda function within this apply() method.

# We add 2 to col1 and assign the value to col3
df["col2"] = df["col1"].apply(lambda x: x+2)
Create a lambda function that adds up 2 to the number

Using a function

See the function that we define, we pass it to the apply method without the ().

Thus every value will be passed to the add_two() method where the value will be the x parameter.

def add_two(x):
	return x + 2

# We add 2 to col1 and assign the value to col3
df["col2"] = df["col1"].apply(add_two)
Pass a function to the apply method to compute the column

Here you are ! You now know how to edit a DataFrame column with Pandas.