Text columns and apply
Python · 15 questions
Short notes
Key idea
The .str accessor runs string methods on a whole column at once. apply runs your own function on each value when no built-in method fits.
Syntax
df["city"].str.strip().str.title()
df["email"].str.lower()
df["name"].str.split(" ").str[0] # first word
df["phone"].str.replace("-", "", regex=False)
df["code"].str[:3]
df["name"].str.contains("raj", case=False, na=False)
df["band"] = df["amount"].apply(lambda x: "high" if x > 1000 else "low")
Example
df["city"] = df["city"].str.strip().str.title()
print(df["city"].value_counts())
" chennai", "CHENNAI" and "Chennai " now count as one city.
Traps
.strmethods return NaN for missing values; passna=Falsewhere you filter.replaceon.strtreats the pattern as a regular expression in some versions; setregex=Falsefor plain text.applywith a Python function is slow on big data. Prefer.str,np.whereor vectorised maths.df.apply(f)runs per column; for rows useaxis=1.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
Which line finds product names containing "book" in any case?
- Question 2medium
Which is the better way to compute
price * stockfor every row? - Question 3medium
What does this print?
print(products["product_name"].str.contains("book", case=False).sum()) - Question 4medium
Every customer email ends in "@example.com". What does this print?
print(customers["email"].str.split("@").str[1].nunique()) - Question 5hard
No product name contains a full stop. What does this print?
print(products["product_name"].str.contains(".").sum())
Text columns and apply
Text columns and apply
Text columns and apply
Text columns and apply
Text columns and apply
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.