0Pricing
Pandas & NumPy Academy · Leçon

Découper et remplacer des chaînes

Découpez les chaînes en plusieurs colonnes avec .str.split(expand=True) et remplacez les sous-chaînes avec .str.replace().

Découper et remplacer des chaînes est une leçon Pandas & NumPy Academy gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Pandas & NumPy Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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     White

Limiting 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.net

rsplit() 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.75

Replacing 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-04

Counting 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-baz

Normalising 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   Analyst

Quick 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.

Questions Fréquemment Posées

La leçon « Découper et remplacer des chaînes » est-elle gratuite ?

Oui — le texte complet de « Découper et remplacer des chaînes » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Pandas & NumPy Academy, passe à CoddyKit PRO. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Découper et remplacer des chaînes » ?

Découpez les chaînes en plusieurs colonnes avec .str.split(expand=True) et remplacez les sous-chaînes avec .str.replace(). Tu pratiques Pandas & NumPy Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Pandas & NumPy Academy ?

Aucune expérience préalable n'est requise. Pandas & NumPy Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Découper et remplacer des chaînes » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Pandas & NumPy Academy ?

Oui. Chaque leçon Pandas & NumPy Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. L’accesseur .str
  2. Découper et remplacer des chaînes
  3. Recherche de motifs avec les expressions régulières
  4. Combiner et nettoyer les colonnes de texte
← Retour à Pandas & NumPy Academy