How to Solve Python AttributeError: ‘Series’ object has no attribute ‘strip’

by | Programming, Python, Tips

In Python, a Pandas Series is a one-dimensional labelled array capable of holding data of any type. Pandas Series is the same as a column in an Excel spreadsheet. If you have string entries in a Series object that you want to strip of whitespace or specified characters, you cannot use the string method strip(). If you try to call the strip() method on a Series object, you will raise the AttributeError: ‘Series’ object has no attribute ‘strip.’

To solve this error, you need to use the Series method pandas.Series.str.strip(). Pandas Series has its own set of methods under the accessor str, which are equivalent to the string methods.

This tutorial will go through the error in detail and how to solve it with code examples.


AttributeError: ‘Series’ object has no attribute ‘strip’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part ‘Series’ object has no attribute ‘strip’ tells us that the Series object we are handling does not have the strip attribute.

The strip() method belongs to the string data type and removes any leading and trailing characters from a string.

Pandas Series has its equivalent method .str.strip(), where str is the string accessor. The method strips whitespace (including newlines) or a set of specified characters from each string of the Series/Index from the left and right. The syntax for the string accessor method str.strip() is as follows:

Series.str.strip(to_strip=None)

Parameters

to_strip: Required. Specifies the set of characters to remove. If None, then remove whitespace. Default is None

Returns

Series or Index of object

Example

Let’s look at an example where we want to strip the string values in the DataFrame column of leading characters. First, let’s look at the data:

id,fruit_type,qty
1,fruit orange,300
2,fruit strawberry,500
3,fruit melon,200

We will save this data in a CSV file called fruit_store.csv. Next, we will load the data into a DataFrame using pandas.

import pandas as pd

df = pd.read_csv('fruit_store.csv')

print(df)
   id        fruit_type  qty
0   1      fruit orange  300
1   2  fruit strawberry  500
2   3       fruit melon  200

The characters ‘fruit ‘ next to the different fruit names is redundant. Let’s try to strip the values in the fruit_type column of the characters ‘fruit ‘.

df['fruit_type'] = df['fruit_type'].strip('fruit ')
print(df)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-bd57b24713d9> in <module>
----> 1 df['fruit_type'] = df['fruit_type'].strip('fruit ')
      2 print(df)

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5581         ):
   5582             return self[name]
-> 5583         return object.__getattribute__(self, name)
   5584 
   5585     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'strip'

The Python interpreter raises an AttributeError because strip() is not a Series method. We can only call strip() directly on string objects.

Solution

To solve this error, we use the string accessor method str.strip(), which is equivalent to the built-in string method strip(). Let’s look at the revised code:

df['fruit_type'] = df['fruit_type'].str.strip('fruit ')

print(df)

Let’s run the code to get the result:

   id  fruit_type  qty
0   1      orange  300
1   2  strawberry  500
2   3       melon  200

We successfully stripped the fruit_type column of the characters ‘fruit ‘.

Summary

Congratulations on reading to the end of this tutorial! The AttributeError ‘Series’ object has no attribute ‘strip’ occurs when you try to call the strip() method on a Series object as if it were a string. To solve this error, you can use the Series method str.strip() where str is the Pandas string accessor attribute.

for further reading on pandas Series, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee