How to edit a DataFrame column with Pandas
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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"])
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)
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)
Here you are ! You now know how to edit a DataFrame column with Pandas.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚