'DataFrame' object has no attribute 'as_matrix

Learn, about an error 'DataFrame' object has no attribute 'as_matrix and how to fix it?
Submitted by Pranit Sharma, on November 23, 2022

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.

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 code 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 »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.