The method apply()
is a pandas method that applies a function along an axis of a DataFrame. The apply() method does not belong to the List data type. If you try to call the apply()
method on a list, you will raise the AttributeError: ‘list’ object has no attribute ‘apply’.
To solve this error, you can convert a list to a DataFrame using pandas.DataFrame(a_list)
. Once you have a DataFrame you can call the apply()
method.
Otherwise, if you want to keep working with a list, you can use map() to apply a function to the elements in the list or a list comprehension.
This tutorial will go through how to solve this error with the help of code examples.
Table of contents
AttributeError: ‘list’ object has no attribute ‘apply’
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 “‘list’ object has no attribute ‘apply’” tells us that the list object we are handling does not have apply()
as an attribute. We will raise this error by calling the apply()
method on a list object. apply() is a pandas.DataFrame method that applies a function along an axis of the provided DataFrame. We can use the apply() method on a DataFrame or on a Series.
Example #1: Cleaning String Using Regex
Let’s look at an example where we want to clean a dataset containing payments made to employees in a company. First, we will define a dictionary containing payments made to two employees.
data = { 'value': [ 'entry1', 'entry2', ], 'txt':[ [ '2019/01/31-11:56:23.288258, 50000, employeeA: paid' ], [ '2019/02/01-11:56:23.288258, 10000, employeeB: paid' ], ] }
Then we will define a function to clean the text of punctuation using the regex
module:
import re def clean_text(text): text = re.sub(r'[^\w\s]','',text) return text
Then, we will iterate over the values of the list under the key ‘txt
‘ and apply a lambda function.
A lambda function is a small anonymous function, in other words, it does not require a def
keyword to give it a name.
The power of lambda functions is the ability to use an anonymous function inside another function.
In this case, we are applying the clean_text()
function using a lambda function inside the apply()
method.
Let’s look at the code:
for payment in data['txt']: payment.apply(lambda x: clean_text(x))
Let’s run the code to see what happens:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-64-8eece2da2ca4> in <module> 1 for payment in data['txt']: ----> 2 payment.apply(lambda x: clean_text(x)) 3 AttributeError: 'list' object has no attribute 'apply'
The error occurs because we are trying to call the apply()
method on a list. The apply()
method belongs to the pandas.DataFrame
class.
Solution: Use DataFrame
To solve this error we can load the data into a DataFrame using pandas.DataFrame()
. With the DataFrame object, we will have access to the DataFrame methods including apply()
. We can then call the apply()
method on the column ‘txt
‘, which is a Series.
# Load data into DataFrame df = pd.DataFrame(data=data) # Confirm type of column print(type(df['txt'])) # Clean the data in the txt column using apply() df['txt'] = df['txt'].apply(lambda x: [clean_text(y) for y in x]) # Convert series to list clean_data = df['txt'].tolist() # Print result for data in clean_data: print(data)
Let’s run the code to see what happens:
<class 'pandas.core.series.Series'> ['20190131115623288258 50000 employeeA paid'] ['20190201115623288258 10000 employeeB paid']
We successfully cleaned the text using the apply()
method on the DataFrame column.
Example #2: Converting Elements in a List
Let’s look at another example where we have a list of numerical strings. We want to convert the numerical strings using the int()
function. We will try to do this using a lambda function within an apply()
call on the list. Let’s look at the code:
lst = ["2", "4", "6", "8", "10", "12"] lst.apply(lambda x: int(x) print(lst)
Let’s run the code to see what happens:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-90-9c918af2bc9f> in <module> 1 lst = ["2", "4", "6", "8", "10", "12"] 2 ----> 3 lst.apply(lambda x: int(x)) 4 5 print(lst) AttributeError: 'list' object has no attribute 'apply'
The error occurs because we are trying to call the apply() method on a list.
Solution #1: Use List Comprehension
To solve this error we can use a list comprehension. List comprehension offers a concise syntax to create a new list based on the values of an existing list. The syntax for list comprehension is:
newlist = [expression for item in iterable if condition == True]
The return value is a new list and the old list is left unchanged. Let’s look at the revised code:
lst = ["2", "4", "6", "8", "10", "12"] int_lst = [int(x) for x in lst] print(int_lst)
The above list comprehension converts each element in the list to an integer. Let’s run the code to see the result:
[2, 4, 6, 8, 10, 12]
We successfully got converted the list of strings to a list of integers.
Solution #2: Use map()
We can also use the map()
function, which executes a specified function for each item in an iterable. The syntax for the map()
function is
map(function, iterable)
Parameters
function
: Required. The function to execute for each item.iterable
: Required. A sequence, collection or an iterator.
Let’s look at the revised code:
lst = ["2", "4", "6", "8", "10", "12"] int_lst = list(map(int, lst)) print(int_lst)
In the above code, the function to apply is int()
and the iterable object is the list of strings. Let’s run the code to get the result:
[2, 4, 6, 8, 10, 12]
We successfully got converted the list of strings to a list of integers.
Summary
Congratulations on reading to the end of this tutorial. The AttributeError: ‘list’ object has no attribute ‘apply’ occurs when you try to use the DataFrame method apply()
on a list. To solve this error you can create a DataFrame object and call the apply()
method on the DataFrame. Otherwise, you can use lambda functions to apply a function to the elements in a list or the map() function.
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
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.