W3docs

Why am I seeing "TypeError: string indices must be integers"?

The "TypeError: string indices must be integers" error is raised when you try to access an element of a DataFrame or Series using a string index instead of an integer index.

The "TypeError: string indices must be integers" error is raised when you try to access a character in a string using a string (or any non-integer type) as the index. In Python, strings are indexed by integers (0, 1, 2...). In pandas, this error frequently occurs when you accidentally treat a string value as a dictionary, or when you iterate over a DataFrame/Series and attempt to use string keys on string data.

Here's an example of how this error can occur:

How the "TypeError: string indices must be integers" is raised in Python

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})

# Extract a string value from the DataFrame
name_str = df['Name'][0]  # Returns 'Alice'

# Try to index the string with another string
# This raises "TypeError: string indices must be integers"
print(name_str['Alice'])

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

The reason behind this error is that Python strings only support integer indexing. When you extract a string from a pandas Series or DataFrame, it becomes a standard Python string. Attempting to use a string key (like dictionary indexing) on it triggers the TypeError. This often happens when you confuse pandas column/row indexing with dictionary key access, or when iterating over rows and mistakenly applying string-based lookups to string values.

The correct way to access data depends on what you're trying to retrieve:

How to resolve the "TypeError: string indices must be integers" in Python

import pandas as pd

df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})

# Correct: Access a single cell using pandas indexing
print(df.loc[0, 'Name'])  # or df.iloc[0, 0]

# Correct: Access a string character using an integer index
name_str = df['Name'][0]
print(name_str[0])  # Returns 'A'

If you intended to work with a dictionary, ensure you're indexing a dictionary object, not a string:

# Correct: Dictionary indexing uses strings
user = {'name': 'Alice', 'age': 25}
print(user['name'])  # Returns 'Alice'

It's always a good idea to check the data type of the object you're indexing. Use type() or print() to verify whether you're working with a string, dictionary, or pandas Series, and apply the appropriate indexing method.