Strings aufteilen und ersetzen
Teilen Sie Strings mit .str.split(expand=True) in mehrere Spalten auf und ersetzen Sie Teilstrings mit .str.replace().
Strings aufteilen und ersetzen ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Strings aufteilen und ersetzen“ kostenlos?
Ja — der vollständige Text von „Strings aufteilen und ersetzen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Strings aufteilen und ersetzen“?
Teilen Sie Strings mit .str.split(expand=True) in mehrere Spalten auf und ersetzen Sie Teilstrings mit .str.replace(). Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Strings aufteilen und ersetzen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Der .str-Accessor
- Strings aufteilen und ersetzen
- Musterabgleich mit regulären Ausdrücken
- Textspalten kombinieren und bereinigen