This error occurs when you try to call the astype()
method on a list as if it were a NumPy ndarray. You can solve this error by converting the list to an array using the numpy.array()
method then call the astype()
method. For example,
import numpy as np lst = [1, 2, 3] arr = np.array(lst) arr = arr.astype('float32')
Otherwise, you can cast an array to a specific dtype using the dtype
parameter in the numpy.array()
method. For example,
import numpy as np lst = [1, 2, 3] arr = np.array(lst,dtype=np.float32)
This tutorial will go through the error and how to solve it with code examples.
Table of contents
AttributeError: ‘list’ object has no attribute ‘astype’
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 ‘astype’” tells us that the list object we are handling does not have the astype attribute. We will raise this error if we call the astype()
method on a list object.
astype() is a ndarray method that returns a copy of an array cast to a specific type.
Example
Let’s look at an example of using the astype()
method. First, we will define a function which calculates the standard deviation of an array.
import numpy as np def get_std(data): data = data.astype('float32') std_val = np.std(data) return std_val
The first line in the function uses the astype()
method to cast the data variable to the dtype float32
.
Next, we will define a list of numeric strings, pass the list to the get_std()
function and print the result to the console.
numbers = ['1', '2', '70', '13', '4', '91'] std = get_std(numbers) print(f'Standard Deviation of list is {std}')
Let’s run the code to see what happens:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [7], in <cell line: 3>() 1 numbers = ['1', '2', '70', '13', '4', '91'] ----> 3 std = get_std(numbers) 5 print(f'Standard Deviation of list is {std}') Input In [6], in get_std(data) 3 def get_std(data): ----> 4 data = data.astype('float32') 5 std_val = np.std(data) 6 return std_val AttributeError: 'list' object has no attribute 'astype'
The error occurs because we tried to call astype()
on the numbers variable, which is a list
object. The astype()
method is not an attribute of the list
data type. We can check what attributes the list
data type has by using the dir()
method. For example,
dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
When we call the dir()
method it returns a list containing the attributes of the specified objects, without the values.
We can check for membership of a specific attribute using the in
operator. If the in
operator evaluates to True
then the attribute exists in the list returned by dir()
. If the in
operator evaluates to values then the attribute does not exist in the list returned by dir()
.
print('astype' in dir(list))
False
The membership check returns False
, verifying that astype()
is not an attribute of the list
data type.
Solution #1: Convert List to Ndarray
We can solve the error by converting the list to a NumPy ndarray using the numpy.array()
method. Let’s look at the revised code:
import numpy as np def get_std(data): data = data.astype('float32') std_val = np.std(data) return std_val numbers = np.array(['1', '2', '70', '13', '4', '91']) std = get_std(numbers) print(f'Standard Deviation of list is {std}')
Let’s run the code to see the result:
Standard Deviation of list is 36.31077194213867
The get_std()
function successfully casts the array to float32
then calculates and returns the standard deviation of the array elements.
Solution #2: Convert List to Ndarray and Use dtype
We can simplify the solution by using the dtype
parameter of the array method. The dtype
parameter sets the desired data type for the array. In this case, we want the array to be float32
. With this change, we can remove the asarray()
call in the get_std()
function. Let’s look at the revised code:
import numpy as np def get_std(data): std_val = np.std(data) return std_val numbers = np.array(['1', '2', '70', '13', '4', '91'], dtype=np.float32) std = get_std(numbers) print(f'Standard Deviation of list is {std}')
Let’s run the code to see the result:
Standard Deviation of list is 36.31077194213867
We successfully calculated the standard deviation of the array and printed the result to the console.
Summary
Congratulations on reading to the end of this tutorial!
For further reading on AttributeErrors, go to the article:
How to Solve Python AttributeError: ‘list’ object has no attribute ‘keys’
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!
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.