TECHNOLOGIESTieInn Technologies

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

  • .str methods return NaN for missing values; pass na=False where you filter.
  • replace on .str treats the pattern as a regular expression in some versions; set regex=False for plain text.
  • apply with a Python function is slow on big data. Prefer .str, np.where or vectorised maths.
  • df.apply(f) runs per column; for rows use axis=1.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Text columns and apply

  1. Question 1easy

    Which line finds product names containing "book" in any case?

  2. Text columns and apply

  3. Question 2medium

    Which is the better way to compute price * stock for every row?

  4. Text columns and apply

  5. Question 3medium

    What does this print?

    print(products["product_name"].str.contains("book", case=False).sum())
  6. Text columns and apply

  7. Question 4medium

    Every customer email ends in "@example.com". What does this print?

    print(customers["email"].str.split("@").str[1].nunique())
  8. Text columns and apply

  9. Question 5hard

    No product name contains a full stop. What does this print?

    print(products["product_name"].str.contains(".").sum())

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.