0Pricing
Pandas & NumPy Academy · Aula

O acessador .str

Acesse métodos de texto em uma Series usando .str e aplique lower(), upper(), strip() e len() a todos os valores.

O acessador .str é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.

Perguntas Frequentes

A aula “O acessador .str” é grátis?

Sim — o texto completo de “O acessador .str” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.

O que vou aprender em “O acessador .str”?

Acesse métodos de texto em uma Series usando .str e aplique lower(), upper(), strip() e len() a todos os valores. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Pandas & NumPy Academy?

Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “O acessador .str”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Pandas & NumPy Academy?

Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. O acessador .str
  2. Dividindo e substituindo textos
  3. Correspondência de padrões com expressões regulares
  4. Combinando e limpando colunas de texto
← Voltar para Pandas & NumPy Academy