'DataFrame' object has no attribute 'as_matrix

Learn, about an error 'DataFrame' object has no attribute 'as_matrix and how to fix it? By Pranit Sharma Last updated : October 05, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

pandas.DataFrame.as_matrix() Method

The as_matrix() method was used to return a NumPy array, this NumPy array is created when a list or any other object is passed inside this method as a parameter but soon after version 0.23.0, this method was declared deprecated.

After version 0.23.0, pandas.DataFrame.to_numpy() method was introduced. The working of pandas.DataFrame.to_numpy() method is also like as_ matrix() method. It returns a NumPy representation of the data frame but only the values in the dataframe will be returned, and the axis labels will be removed.

Let us understand with the help of an example,

Python program to demonstrate the 'DataFrame' object has no attribute 'as_matrix and how to fix it?

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dataframe
df = pd.DataFrame(data=np.random.randint(0,50,(2,5)),columns=list('12345'))

# Display original DataFrame
print("Original DataFrame 1:\n",df,"\n")

# using as_matrix
res = df.as_matrix()

# Display Result
print('Result:\n',res)

Output:

Example 1: 'DataFrame' object has no attribute 'as_matrix

Now, use df.to_numpy() instead of as_matrix().

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dataframe
df = pd.DataFrame(data=np.random.randint(0,50,(2,5)),columns=list('12345'))

# Display original DataFrame
print("Original DataFrame 1:\n",df,"\n")

# using as_matrix
res = df.to_numpy()

# Display Result
print('Result:\n',res)

Output:

Example 2: 'DataFrame' object has no attribute 'as_matrix

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.