拆分与替换字符串
使用 .str.split(expand=True) 将字符串拆分为多个列,并使用 .str.replace() 替换子字符串。
拆分与替换字符串 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Splitting Strings into a List
.str.split(sep) splits each string in a Series at every occurrence of the separator and returns a Series of lists. Without expand=True, each element is a Python list, which is useful for counting tokens or further list-level processing. The separator can be a literal string or a regex pattern.
import pandas as pd
df = pd.DataFrame({'tags': ['python,data,pandas', 'ml,ai', 'sql,db,query']})
# Split into a list of strings
df['tag_list'] = df['tags'].str.split(',')
print(df['tag_list'])
# 0 [python, data, pandas]
# 1 [ml, ai]
# 2 [sql, db, query]
# Count tags per row
df['tag_count'] = df['tag_list'].str.len()
print(df['tag_count'].tolist()) # [3, 2, 3]expand=True to Split into Columns
Passing expand=True to .str.split() returns a DataFrame instead of a Series of lists, where each split token becomes its own column (column 0, 1, 2, …). This is the standard way to widen a delimited column — for example, splitting a 'first last' full name into separate first and last name columns.
import pandas as pd
df = pd.DataFrame({'full_name': ['Alice Smith', 'Bob Jones', 'Carol White']})
# Split into two columns
name_parts = df['full_name'].str.split(' ', expand=True)
name_parts.columns = ['first_name', 'last_name']
df = pd.concat([df, name_parts], axis=1)
print(df)
# full_name first_name last_name
# 0 Alice Smith Alice Smith
# 1 Bob Jones Bob Jones
# 2 Carol White Carol WhiteLimiting Split Count with n=
The n parameter limits the maximum number of splits. .str.split(sep, n=1) splits at most once, creating at most two parts. This is useful when you only need the first component of a string and the rest can stay together — for example, extracting the domain from an email by splitting at '@'.
import pandas as pd
df = pd.DataFrame({'email': ['alice@example.com', 'bob@work.org', 'carol@test.net']})
# Split at '@', keep only the first split
parts = df['email'].str.split('@', n=1, expand=True)
df['username'] = parts[0]
df['domain'] = parts[1]
print(df[['username', 'domain']])
# username domain
# 0 alice example.com
# 1 bob work.org
# 2 carol test.netrsplit() for Right-Side Splitting
.str.rsplit(sep, n=1) splits from the right side of the string. This is useful when you want the last component — for example, extracting the file extension from a path by splitting at the last dot. Combined with expand=True, it creates two columns: everything before the last separator and everything after.
import pandas as pd
df = pd.DataFrame({'filepath': ['data/raw/sales.csv', 'data/clean/orders.xlsx', 'reports/q1.pdf']})
# Split on the last '/' to separate directory from filename
parts = df['filepath'].str.rsplit('/', n=1, expand=True)
df['directory'] = parts[0]
df['filename'] = parts[1]
print(df[['directory', 'filename']])
# directory filename
# 0 data/raw sales.csv
# 1 data/clean orders.xlsx
# 2 reports q1.pdf.str.replace() for Substring Substitution
.str.replace(pat, repl) replaces occurrences of a pattern in each string. By default, pat is treated as a regular expression, so pass regex=False for literal string replacement. The replacement can be a fixed string or a regex backreference. Always use this for vectorised substitution instead of a Python loop.
import pandas as pd
df = pd.DataFrame({'price': ['$1,200.50', '$800.00', '$3,450.75']})
# Remove dollar sign and commas
df['price_clean'] = (
df['price']
.str.replace('$', '', regex=False) # literal $
.str.replace(',', '', regex=False) # literal comma
)
df['price_float'] = df['price_clean'].astype(float)
print(df)
# price price_clean price_float
# 0 $1,200.50 1200.50 1200.5
# 1 $800.00 800.00 800.0
# 2 $3,450.75 3450.75 3450.75Replacing with Regex Patterns
When you pass regex=True (the default), the pattern is a regular expression and the replacement can include backreferences like r'\1' to refer to captured groups. This enables powerful text transformations like reformatting dates, normalising phone numbers, or extracting structured data from free text.
import pandas as pd
df = pd.DataFrame({'date': ['01-15-2024', '03-20-2024', '07-04-2024']})
# Reformat from MM-DD-YYYY to YYYY-MM-DD using groups
df['date_iso'] = df['date'].str.replace(
r'(\d{2})-(\d{2})-(\d{4})',
r'\3-\1-\2',
regex=True
)
print(df)
# date date_iso
# 0 01-15-2024 2024-01-15
# 1 03-20-2024 2024-03-20
# 2 07-04-2024 2024-07-04Counting Replacements Made
Sometimes you want to verify how many values were actually modified by a replacement. Compare the original and replaced Series to count rows where a change occurred. This validation step confirms that the replace pattern matched as expected and helps catch regex mistakes early.
import pandas as pd
df = pd.DataFrame({'text': ['foo bar', 'hello foo', 'world', 'foo foo']})
original = df['text'].copy()
df['text'] = df['text'].str.replace('foo', 'baz', regex=False)
changed = (df['text'] != original).sum()
print(f'{changed} rows were modified') # 3
print(df['text'].tolist())
# ['baz bar', 'hello baz', 'world', 'baz baz']Replacing Multiple Patterns with a Loop
When you need to apply many substitutions (e.g., standardising dozens of abbreviations), loop over a mapping dictionary and apply each replacement in sequence. This is more maintainable than one complex regex alternation. Build the mapping from business rules or a lookup table.
import pandas as pd
df = pd.DataFrame({'dept': ['Eng', 'Engg', 'HR', 'Human Resources', 'Mktg', 'Marketing']})
# Standardisation map
substitutions = {
'Engg': 'Engineering',
'Eng': 'Engineering',
'Human Resources': 'HR',
'Mktg': 'Marketing'
}
for old, new in substitutions.items():
df['dept'] = df['dept'].str.replace(old, new, regex=False)
print(df['dept'].tolist())
# ['Engineering', 'Engineering', 'HR', 'HR', 'Marketing', 'Marketing']Joining Split Parts Back Together
After splitting, you may need to recombine parts. For a Series of lists, use .str.join(separator) to concatenate the list elements into a single string per row. For joining values across columns, use the standard string concatenation with + and .astype(str).
import pandas as pd
df = pd.DataFrame({'parts': [['alpha', 'beta'], ['foo', 'bar', 'baz']]})
# Join list elements with a hyphen
df['joined'] = df['parts'].str.join('-')
print(df['joined'])
# 0 alpha-beta
# 1 foo-bar-bazNormalising Whitespace
A common text cleaning task is collapsing multiple consecutive spaces into a single space. This often happens in scraped text where HTML spacing or copy-paste adds extra whitespace. The regex pattern r'\s+' matches one or more whitespace characters and replaces them all with a single space, then .str.strip() removes any leading or trailing space.
import pandas as pd
df = pd.DataFrame({'address': ['123 Main St', ' 456 Oak Ave ', '789 Pine St']})
df['address_clean'] = (
df['address']
.str.replace(r'\s+', ' ', regex=True)
.str.strip()
)
print(df['address_clean'].tolist())
# ['123 Main St', '456 Oak Ave', '789 Pine St']Practical: Parsing a Structured String Column
Here is a realistic example where a single column contains structured data like 'Alice:25:Engineer'. We split on the delimiter, name the resulting columns, and convert each to its appropriate type — a complete parse-and-type-convert pipeline using only .str.split() and astype().
import pandas as pd
df = pd.DataFrame({'record': ['Alice:25:Engineer', 'Bob:34:Manager', 'Carol:28:Analyst']})
parts = df['record'].str.split(':', expand=True)
parts.columns = ['name', 'age', 'role']
parts['age'] = parts['age'].astype(int)
result = pd.concat([df, parts], axis=1)
print(result)
# record name age role
# 0 Alice:25:Engineer Alice 25 Engineer
# 1 Bob:34:Manager Bob 34 Manager
# 2 Carol:28:Analyst Carol 28 AnalystQuick Check
Test your understanding of splitting and replacing strings.
Lesson Recap
In this lesson you learned: str.split(sep, expand=True) widens a delimited column into multiple columns, n= limits the number of splits, str.rsplit() splits from the right, and str.replace() substitutes patterns (with regex support). Chain split and replace operations with strip and lower to build complete text normalisation pipelines. Next up we use regex patterns to extract and match substrings.
常见问题解答
「拆分与替换字符串」课时是免费的吗?
是的 — 「拆分与替换字符串」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「拆分与替换字符串」这节课中我会学到什么?
使用 .str.split(expand=True) 将字符串拆分为多个列,并使用 .str.replace() 替换子字符串。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「拆分与替换字符串」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- .str 访问器
- 拆分与替换字符串
- 使用正则表达式匹配模式
- 合并与清理文本列