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

Dung Do Tien Jul 03 2022 45

I try to create a Python application that will help me import and process a CSV file. My code is like this:

main.py 

 import pandas as pd
df = pd.read_csv('courses.csv')
arr = df.as_matrix() #convert the DataFrame to a NumPy array
print(arr)

And here is the format data of courses.csv file:

 name,time,price
Connect Skills,30,£90.09
Management Time,25,£80.10
LeaderShip,40,£10.19
Friend and family,£24.01

My code will load & read that CSV file, and use as_matrix() method to help convert the DataFrame to a Numpy array. But it didn't work and throw an exception AttributeError: 'DataFrame' object has no attribute 'as_matrix'. You can see detailed exceptions here:

 Traceback (most recent call last):
  File "main.py", line 4, in <module>
    arr = df.as_matrix() #convert the DataFrame to a NumPy array
  File "/usr/lib/python3.8/site-packages/pandas/core/generic.py", line 5130, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'as_matrix'


** Process exited - Return Code: 1 **
Press Enter to exit terminal

I used Python 3.10. Anyone can explain and solve the issue to help me?

Thanks in advance.

Have 1 answer(s) found.
  • J

    Juckke G Jul 03 2022

    To solve this issue please don't use as_matrix() method. You can use values property to do. See an example below:

     import pandas as pd
    df = pd.read_csv('courses.csv')
    arr = df.values
    print(arr)

    #Output

     [['Connect Skills' '30' '£90.09']
    ['Management Time' '25' '£80.10']
    ['LeaderShip' '40' '£10.19']
    ['Friend and family' '£24.01' nan]]

    I hope this answer is useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close