简体   繁体   中英

AttributeError: 'Series' object has no attribute 'as_matrix' Why is it error?

When I execute the code of the official website, I get such an error. Why? code show as follow:

landmarks_frame = pd.read_csv(‘F:\OfficialData\faces\face_landmarks.csv’)
n = 65
img_name = landmarks_frame.iloc[n, 0]
landmarks = landmarks_frame.iloc[n, 1:].as_matrix()
landmarks = landmarks.astype(‘float’).reshape(-1, 2)

List item

As stated in another answer, the as_matrix method is deprecated since 0.23.0, so you should use to_numpy instead. However, I want to highlight the fact that as_matrix and to_numpy have different signatures: as_matrix takes a list of column names as one of its parameter, in case you want to limit the conversion to a subset of the original DataFrame; to_numpy does not accept such a parameter. As a consequence, the two methods are completely interchangeable only if you want to convert the DataFrame in full. If you (as in my case) need to convert a subset of the matrix, the usage would be quite different in the two use cases.

For example let's assume we only need to convert the subset ['col1', 'col2', 'col4'] of our original DataFrame to a Numpy array. In that case you might have some legacy code relying on as_matrix to convert, which looks more or less like:

df.as_matrix(['col1', 'col2', 'col4'])

While converting the above code to to_numpy you cannot simply replace the function name like in:

df.to_numpy(['col1', 'col2', 'col4'])  # WRONG

because to_numpy does not accept a subset of columns as parameter. The solution in that case would be to do the selection first, and apply to_numpy to the result, as in:

df[['col1', 'col2', 'col4']].to_numpy()  # CORRECT

The purpose of as_matrix method is to

Convert the frame to its Numpy-array representation.

as_matrix method is deprecated since 0.23.0
0.25.1 documentation says : Deprecated since version 0.23.0: Use DataFrame.values() instead

The two alternatives are

  1. .values() : Returns numpy.ndarray
  2. .to_numpy() : Returns numpy.ndarray

However, .values() documentation gives another warning :- Warning We recommend using DataFrame.to_numpy() instead.

I got the error in a slightly different way : AttributeError: 'DataFrame' object has no attribute 'as_matrix'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM