python - 属性错误 : 'Series' object has no attribute 'as_matrix' Why is it error?

标签 python pandas numpy

当我执行官网的代码时,出现这样的错误。为什么?
代码显示如下:

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

最佳答案

正如另一个答案中所述,as_matrix方法自 0.23.0 起已弃用,因此您应该使用 to_numpy反而。但是,我想强调一个事实,即 as_matrixto_numpy有不同的签名:as_matrix将列名列表作为其参数之一,以防您想将转换限制为原始 DataFrame 的子集; to_numpy不接受这样的参数。因此,只有当您想完全转换 DataFrame 时,这两种方法才完全可以互换。如果您(如我的情况)需要转换矩阵的子集,则两种用例的用法将大不相同。

例如,假设我们只需要将原始 DataFrame 的子集 ['col1', 'col2', 'col4'] 转换为 Numpy 数组。在这种情况下,您可能有一些依赖于 as_matrix 的遗留代码。转换,它看起来或多或少像:

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

同时将上述代码转换为 to_numpy您不能简单地替换函数名称,如:
df.to_numpy(['col1', 'col2', 'col4'])  # WRONG

因为 to_numpy不接受列的子集作为参数。在这种情况下的解决方案是先进行选择,然后应用 to_numpy结果,如:
df[['col1', 'col2', 'col4']].to_numpy()  # CORRECT

关于python - 属性错误 : 'Series' object has no attribute 'as_matrix' Why is it error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164560/

相关文章:

python - Pandas:如何根据条件按列设置另一列的值

python - 将多维数组中的选定值追加到新数组

python - 如何简化 numpy 条件语句来查找给定值的元素的相邻索引?

python struct module - 解包时的奇数

Python 类型错误 : 'NoneType' object has no attribute '__getitem__

Python/Pandas - 从地址中删除街道号码

python - 使用 Pytorch 显示增强图像

python - 如何确保 tensorflow 正在使用 GPU

python - 在 Qt Creator 中开发 Python 应用程序

python - 在包含项目列表的列中查找共同值