How to Fix AttributeError: ‘DataFrame’ object has no attribute ‘as_matrix’

Diagram of How to Fix AttributeError: 'DataFrame' object has no attribute 'as_matrix'

Diagram

AttributeError: ‘Dataframe’ object has no attribute ‘as_matrix’ error occurs when you try to “use the as_matrix() method on a Pandas DataFrame.” The as_matrix() method was “deprecated in Pandas 0.23.0 and removed in Pandas 1.0.0.”

To fix the AttributeError: ‘Dataframe’ object has no attribute ‘as_matrix’ error, you can use the “.values” attribute or “to_numpy()” method.

Reproduce the error

import pandas as pd
import numpy as np

# Create a simple DataFrame
df = pd.DataFrame(np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]]),
 columns=['a', 'b', 'c'])

# Attempt to convert DataFrame to NumPy array using as_matrix()
matrix = df.as_matrix()
print(matrix)

Output

AttributeError: 'DataFrame' object has no attribute 'as_matrix'

How to fix it?

Solution 1: Using the .values attribute

import pandas as pd
import numpy as np

# Create a simple DataFrame
df = pd.DataFrame(np.array([[1, 2, 3],
                            [4, 5, 6],
                            [7, 8, 9]]),
 columns=['a', 'b', 'c'])

matrix = df.values
print(matrix)

Output

[[1 2 3]
 [4 5 6]
 [7 8 9]]

Solution 2: Using the to_numpy() method

Pandas DataFrame to_numpy() method returns the NumPy representation of the DataFrame but allows you to specify the data type.

import pandas as pd
import numpy as np

# Create a simple DataFrame
df = pd.DataFrame(np.array([[1, 2, 3],
                            [4, 5, 6],
                            [7, 8, 9]]),
 columns=['a', 'b', 'c'])

matrix = df.to_numpy()
print(matrix)

Output

[[1 2 3]
 [4 5 6]
 [7 8 9]]

You can replace the as_matrix() function with either values or to_numpy() in your code to fix the error.

That’s it!

Related posts

AttributeError: ‘DataFrame’ object has no attribute ‘_jdf’

AttributeError: ‘DataFrame’ object has no attribute ‘str’

AttributeError: ‘DataFrame’ object has no attribute ‘map’

AttributeError: ‘DataFrame’ object has no attribute ‘reshape’

AttributeError: ‘DataFrame’ object has no attribute ‘iteritems’

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.