Replace scalar values using .replace()

Writing Efficient Code with pandas

Leonidas Souliotis

PhD Candidate

The popular name dataset

Year of Birth Gender Ethnicity Child's First Name Count Rank
2011 FEMALE ASIAN AND PACIFIC ISLANDER SOPHIA 119 1
2011 FEMALE ASIAN AND PACIFIC ISLANDER CHLOE 106 2
Writing Efficient Code with pandas

Replace values in pandas

start_time = time.time()
names['Gender'].loc[names.Gender=='MALE'] = 'BOY'
print("Replace values using .loc[]: {} sec".format(time.time() - start_time))
Results from the first method calculated in 0.0311849 seconds
Writing Efficient Code with pandas

Replace values using .replace()

start_time = time.time()
names['Gender'].replace('MALE', 'BOY', inplace=True)
print("Time using .replace(): {} sec".fomrat(time.time() - start_time))
Time using .replace(): 0.0016758441925 sec
Differerence in speed: 1,704.52411439%
Writing Efficient Code with pandas

Let's do it

Writing Efficient Code with pandas

Preparing Video For Download...