.str 访问器
使用 .str 访问 Series 上的字符串方法,并对所有值应用 lower()、upper()、strip() 和 len()。
.str 访问器 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Introduction to the .str Accessor
Python strings have many useful methods like .lower(), .strip(), and .replace(), but you cannot call them directly on a Pandas Series of strings — you would need a loop. The .str accessor solves this by exposing vectorised versions of Python's built-in string methods on a Series, applying the operation to every element at once without writing a loop and handling NaN gracefully (it returns NaN for missing values).
import pandas as pd
names = pd.Series([' Alice ', 'BOB', ' carol '])
# .strip() removes leading/trailing whitespace from every element
print(names.str.strip())
# 0 Alice
# 1 BOB
# 2 carol
# .lower() lowercases every element
print(names.str.strip().str.lower())
# 0 alice
# 1 bob
# 2 carolCase Conversion Methods
Inconsistent capitalisation is one of the most common data quality issues. The .str accessor provides .lower(), .upper(), .title() (first letter of each word capitalised), and .capitalize() (only first letter of the string). Use .lower() before comparisons and groupby operations to avoid treating 'NYC' and 'nyc' as different groups.
import pandas as pd
df = pd.DataFrame({'city': ['new york', 'LOS ANGELES', 'Chicago', 'HOUSTON']})
df['city_lower'] = df['city'].str.lower()
df['city_title'] = df['city'].str.title()
df['city_upper'] = df['city'].str.upper()
print(df[['city_lower', 'city_title']])
# city_lower city_title
# 0 new york New York
# 1 los angeles Los Angeles
# 2 chicago Chicago
# 3 houston HoustonStripping Whitespace
Leading and trailing whitespace is invisible in displays but causes exact-match comparisons to silently fail. .str.strip() removes whitespace from both ends, .str.lstrip() removes from the left only, and .str.rstrip() removes from the right only. You can also pass a specific character to strip (e.g., .str.strip('$') removes dollar signs).
import pandas as pd
df = pd.DataFrame({'code': [' A001 ', '$B002$', ' C003']})
print(df['code'].str.strip()) # 'A001', '$B002$', 'C003'
print(df['code'].str.strip('$ ')) # 'A001', 'B002', 'C003'Checking Length with .str.len()
.str.len() returns the number of characters in each string element as an integer Series. This is useful for validation — checking that a product code is always 5 characters, that a phone number has the right digit count, or that a text field is not suspiciously short (e.g., a single character suggesting a placeholder).
import pandas as pd
df = pd.DataFrame({'sku': ['A001', 'BB02', 'CCC', 'D0005', 'E1']})
df['sku_len'] = df['sku'].str.len()
print(df)
# Rows with unexpected SKU length
bad_skus = df[df['sku_len'] != 4]
print(bad_skus)
# sku sku_len
# 2 CCC 3
# 3 D0005 5
# 4 E1 2Checking Prefixes and Suffixes
.str.startswith() and .str.endswith() return boolean Series. These are the cleanest way to filter rows based on how a string value begins or ends — for example, selecting all order IDs that start with 'ORD' or all file names that end with '.csv'. They also accept tuples of strings to check multiple prefixes/suffixes at once.
import pandas as pd
df = pd.DataFrame({'file': ['data.csv', 'report.xlsx', 'backup.csv', 'config.json']})
# Filter CSV files
csv_files = df[df['file'].str.endswith('.csv')]
print(csv_files)
# file
# 0 data.csv
# 2 backup.csv
# Multiple suffixes
spreadsheets = df[df['file'].str.endswith(('.csv', '.xlsx'))]
print(spreadsheets.shape) # (3, 1).str.contains() for Substring Search
.str.contains(pattern) returns a boolean Series indicating whether each element contains the given pattern. By default it accepts a regular expression, but you can pass regex=False for a literal substring search. The na=False argument treats NaN as not matching instead of propagating NaN to the result.
import pandas as pd
df = pd.DataFrame({
'description': ['Red apple', 'Green banana', 'Red cherry', None, 'Blue grape']
})
# Find rows containing 'Red' (case-sensitive)
mask = df['description'].str.contains('Red', na=False)
print(df[mask])
# description
# 0 Red apple
# 2 Red cherryNaN Behaviour in .str Methods
When a Series contains NaN values, most .str methods propagate NaN by default — they return NaN for the missing positions in the output Series. Methods that return boolean values (like .str.contains()) default to returning NaN for missing positions, which can cause issues with boolean indexing. Use na=False to treat NaN as non-matching, or na=True to treat it as matching.
import pandas as pd
import numpy as np
s = pd.Series(['hello', None, 'world', np.nan])
# Default: NaN propagates
print(s.str.upper())
# 0 HELLO
# 1 None
# 2 WORLD
# 3 NaN
# contains with na=False: NaN treated as non-matching
print(s.str.contains('o', na=False))
# 0 True
# 1 False
# 2 True
# 3 False.str.count() for Pattern Frequency
.str.count(pattern) counts the number of times a pattern appears in each string element. This is useful for feature engineering in natural language processing — for example, counting how many times a word appears, how many digits a string contains, or how many commas separate values in a delimited field.
import pandas as pd
df = pd.DataFrame({'text': ['hello world', 'foo bar baz', 'a b c d e']})
# Count number of words (spaces + 1)
df['word_count'] = df['text'].str.count(' ') + 1
print(df)
# text word_count
# 0 hello world 2
# 1 foo bar baz 3
# 2 a b c d e 5Chaining .str Methods
Because each .str method returns a new Series, you can chain multiple string operations in one expression. This is the cleanest way to apply several cleaning steps to a text column: strip whitespace, lowercase, and remove special characters — all in a single readable line. The chain evaluates left to right, with each step feeding into the next.
import pandas as pd
df = pd.DataFrame({'tag': [' Python ', ' DATA-SCIENCE ', ' Machine_Learning !']})
df['tag_clean'] = (
df['tag']
.str.strip()
.str.lower()
.str.replace('[-_!]', ' ', regex=True)
.str.strip()
)
print(df)
# tag tag_clean
# 0 Python python
# 1 DATA-SCIENCE data science
# 2 Machine_Learning ! machine learningIndexing Characters with .str[]
The .str[n] notation extracts the character at position n from each string, and .str[start:end] extracts a substring slice. This is vectorised indexing into the strings, useful for extracting fixed-width codes like postal code prefixes, year digits from date strings, or the first letter of a name.
import pandas as pd
df = pd.DataFrame({'code': ['NYC-001', 'LAX-042', 'ORD-018']})
# Extract city code (first 3 chars)
df['city'] = df['code'].str[:3]
# Extract numeric part (chars 4 onwards)
df['num'] = df['code'].str[4:]
print(df)
# code city num
# 0 NYC-001 NYC 001
# 1 LAX-042 LAX 042
# 2 ORD-018 ORD 018Practical Cleaning with .str
Here is a realistic text cleaning pipeline for a product name column that was scraped from a web page. It combines stripping, case normalisation, punctuation removal, and whitespace collapse — a standard pre-processing sequence in any NLP or data cleaning task.
import pandas as pd
df = pd.DataFrame({
'product': [' Apple iPhone 15!!', 'samsung GALAXY s24 ', ' Google Pixel 8 Pro ']
})
df['product_clean'] = (
df['product']
.str.strip()
.str.title()
.str.replace('[^A-Za-z0-9 ]', '', regex=True) # remove punctuation
.str.replace(r'\s+', ' ', regex=True) # collapse extra spaces
.str.strip()
)
print(df['product_clean'].tolist())
# ['Apple Iphone 15', 'Samsung Galaxy S24', 'Google Pixel 8 Pro']Quick Check
Test your understanding of the .str accessor.
Lesson Recap
In this lesson you learned: the .str accessor exposes vectorised string methods on a Pandas Series, including lower/upper/strip for normalisation, startswith/endswith/contains for filtering, and len/count for measurement. Chain multiple .str calls to build readable cleaning pipelines. Use na=False when NaN values are present. Next up we split and replace strings for more advanced transformations.
常见问题解答
「.str 访问器」课时是免费的吗?
是的 — 「.str 访问器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「.str 访问器」这节课中我会学到什么?
使用 .str 访问 Series 上的字符串方法,并对所有值应用 lower()、upper()、strip() 和 len()。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「.str 访问器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- .str 访问器
- 拆分与替换字符串
- 使用正则表达式匹配模式
- 合并与清理文本列