Working with Text Data
Pandas - Working with Text Data
Section titled “Pandas - Working with Text Data”Text data (strings) is ubiquitous, and Pandas provides powerful and efficient tools for manipulating string data stored in Series or Index objects. These tools are accessed via the .str accessor.
A key advantage of using the .str accessor is that its methods automatically handle missing values (NaN), typically returning NaN for any operation involving a missing value, thus preventing errors.
Most .str methods mirror the standard Python string methods (like .lower(), .split(), .replace(), etc.) but are vectorized, meaning they operate on the entire Series efficiently without needing explicit Python loops.
Let’s explore some common string operations using a sample Series:
import pandas as pdimport numpy as np
s = pd.Series([' Tom ', 'William Rick', 'JOHN', ' Alber@t', np.nan, '12345', 'Steve Smith ', 'Python & Pandas'])
print("Original Series:")print(s)Original Series Output:
0 Tom1 William Rick2 JOHN3 Alber@t4 NaN5 123456 Steve Smith7 Python & Pandasdtype: objectCommon String Methods via .str Accessor
Section titled “Common String Methods via .str Accessor”| Method | Description |
|---|---|
.str.lower() | Converts strings to lower case. |
.str.upper() | Converts strings to upper case. |
.str.len() | Computes the length of each string. |
.str.strip() | Removes leading and trailing whitespace (including newlines). |
.str.lstrip() | Removes leading whitespace. |
.str.rstrip() | Removes trailing whitespace. |
.str.split(pat=None, n=-1, expand=False) | Splits each string by the specified separator/pattern (pat). Returns a Series of lists by default, or a DataFrame if expand=True. |
.str.cat(sep='') | Concatenates strings in the Series/Index with a given separator. |
.str.contains(pat, case=True, regex=True) | Checks if a pattern (pat) is contained within each string. Returns a boolean Series. |
.str.startswith(pat) | Checks if each string starts with the specified pattern (pat). Returns a boolean Series. |
.str.endswith(pat) | Checks if each string ends with the specified pattern (pat). Returns a boolean Series. |
.str.replace(pat, repl, n=-1, regex=True) | Replaces occurrences of pat with repl in each string. |
.str.repeat(repeats) | Repeats each string repeats times. |
.str.count(pat) | Counts occurrences of pat within each string. |
.str.find(sub) | Returns the lowest index of the substring sub in each string; returns -1 if not found. |
.str.findall(pat) | Finds all occurrences of the pattern pat (can be regex) in each string; returns a Series of lists. |
.str.get(i) | Extracts the element at position i for each string (if it’s indexable). |
.str.slice(start=None, stop=None, step=None) | Slices substrings from each element in the Series/Index. |
.str.islower(), .str.isupper(), .str.isnumeric(), etc. | Checks character properties for each string (e.g., all lowercase, all uppercase, all numeric). Returns a boolean Series. |
pd.get_dummies(s) or s.str.get_dummies(sep='|') | Converts categorical string data into dummy/indicator variables (One-Hot Encoding). Can split strings by sep first. |
Examples
Section titled “Examples”Let’s apply some of these methods to our sample Series s.
# Case Conversionprint("\n--- Case Conversion ---")print("Lower Case:\n", s.str.lower())print("\nUpper Case:\n", s.str.upper())
# Lengthprint("\n--- Length ---")print("String Lengths:\n", s.str.len())
# Stripping Whitespaceprint("\n--- Stripping Whitespace ---")print("Stripped (both sides):\n", s.str.strip())print("\nLeft Stripped:\n", s.str.lstrip())print("\nRight Stripped:\n", s.str.rstrip())
# Splittingprint("\n--- Splitting ---")# Split by space, return listsprint("Split by space (into lists):\n", s.str.split(' '))# Split by space, expand into DataFrame columnsprint("\nSplit by space (expand=True):\n", s.str.split(' ', expand=True))
# Checking Contentprint("\n--- Checking Content ---")print("Contains 'Rick'?\n", s.str.contains('Rick'))print("\nStarts with 'P'?\n", s.str.startswith('P'))print("\nEnds with ' '?\n", s.str.endswith(' '))
# Replacingprint("\n--- Replacing ---")print("Replace '@' with '#':\n", s.str.replace('@', '#'))print("\nReplace ' ' with '_':\n", s.str.replace(' ', '_')) # Note: affects internal spaces too
# Find / Countprint("\n--- Find / Count ---")print("Find first 'e':\n", s.str.find('e'))print("\nCount occurrences of 'n':\n", s.str.count('n'))
# Character Type Checksprint("\n--- Character Type Checks ---")print("Is Lowercase?\n", s.str.islower())print("\nIs Uppercase?\n", s.str.isupper())print("\nIs Numeric?\n", s.str.isnumeric())
# Get Dummies (Example on a simpler series)s_cat = pd.Series(['A|B', 'B', 'A|C', 'A'])print("\n--- Get Dummies --- ")print("Categorical Series:\n", s_cat)print("\nDummy Variables (split by '|'):\n", s_cat.str.get_dummies(sep='|'))Example Output Snippets:
--- Case Conversion ---Lower Case: 0 tom1 william rick2 john3 alber@t4 NaN5 123456 steve smith7 python & pandasdtype: object
Upper Case: 0 TOM1 WILLIAM RICK2 JOHN3 ALBER@T4 NaN5 123456 STEVE SMITH7 PYTHON & PANDASdtype: object
--- Length ---String Lengths: 0 9.01 12.02 4.03 8.04 NaN5 5.06 12.07 15.0dtype: float64
--- Stripping Whitespace ---Stripped (both sides): 0 Tom1 William Rick2 JOHN3 Alber@t4 NaN5 123456 Steve Smith7 Python & Pandasdtype: object...--- Splitting ---Split by space (into lists): 0 [, , , Tom, , , ]1 [William, Rick]2 [JOHN]3 [, Alber@t]4 NaN5 [12345]6 [Steve, Smith, ]7 [Python, &, Pandas]dtype: object
Split by space (expand=True): 0 1 20 Tom1 William Rick None2 JOHN None None3 Alber@t None4 None None None5 12345 None None6 Steve Smith7 Python & Pandas...--- Checking Content ---Contains 'Rick'? 0 False1 True2 False3 False4 NaN5 False6 False7 Falsedtype: object...--- Replacing ---Replace '@' with '#': 0 Tom1 William Rick2 JOHN3 Alber#t4 NaN5 123456 Steve Smith7 Python & Pandasdtype: object...--- Find / Count ---Find first 'e': 0 -1.01 3.02 -1.03 4.04 NaN5 -1.06 3.07 -1.0dtype: float64
Count occurrences of 'n': 0 0.01 1.02 1.03 0.04 NaN5 0.06 0.07 2.0dtype: float64...--- Get Dummies ---Categorical Series: 0 A|B1 B2 A|C3 Adtype: object
Dummy Variables (split by '|'): A B C0 1 1 01 0 1 02 1 0 13 1 0 0These vectorized string methods provided by the .str accessor are essential for cleaning, preparing, and analyzing text data efficiently within Pandas.