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’

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.