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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)