0Pricing
Pandas & NumPy Academy · Lección

El accessor .str

Acceda a los métodos de texto de una Series mediante .str y aplique lower(), upper(), strip() y len() a todos los valores.

El accessor .str es una lección gratuita de Pandas & NumPy Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Pandas & NumPy Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Pandas & NumPy Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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    carol

Case 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      Houston

Stripping 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        2

Checking 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 cherry

NaN 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           5

Chaining .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 learning

Indexing 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 018

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

Preguntas frecuentes

¿La lección «El accessor .str» es gratis?

Sí — el texto completo de «El accessor .str» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Pandas & NumPy Academy, actualiza a CoddyKit PRO. El curso de Pandas & NumPy Academy incluye 4 lecciones en total.

¿Qué aprenderé en «El accessor .str»?

Acceda a los métodos de texto de una Series mediante .str y aplique lower(), upper(), strip() y len() a todos los valores. Practicas Pandas & NumPy Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Pandas & NumPy Academy?

No se requiere experiencia previa. Pandas & NumPy Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «El accessor .str»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Pandas & NumPy Academy?

Sí. Cada lección de Pandas & NumPy Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. El accessor .str
  2. Dividir y reemplazar cadenas
  3. Coincidencia de patrones con regex
  4. Combinar y limpiar columnas de texto
← Volver a Pandas & NumPy Academy