【问题标题】:AttributeError: 'Series' object has no attribute 'as_matrix' Why is it error?AttributeError: 'Series' object has no attribute 'as_matrix' 为什么会出错?
【发布时间】:2020-05-26 14:34:24
【问题描述】:

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

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)

列表项

【问题讨论】:

  • 哪个官网?能否提供数据集的链接?
  • pd.DataFrame.as_matrix 自 0.23.0 版以来已被弃用;你应该改用DataFrame.to_numpy()
  • 感谢您的帮助。用DataFrame.to_numpy()替换它
  • 我以不同的方式得到了错误:AttributeError: 'DataFrame' object has no attribute 'as_matrix'

标签: python pandas numpy


【解决方案1】:

正如另一个答案中所述,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

【讨论】:

    【解决方案2】:

    as_matrix方法的目的是为了

    将帧转换为其 Numpy 数组表示。

    as_matrix 方法自 0.23.0 起已弃用
    0.25.1 documentation 表示:自 0.23.0 版起已弃用:改用 DataFrame.values()

    这两种选择是

    1. .values() : 返回 numpy.ndarray
    2. .to_numpy() : 返回 numpy.ndarray

    但是,.values() documentation 给出了另一个警告:- Warning We recommend using DataFrame.to_numpy() instead.

    我得到错误的方式略有不同:AttributeError: 'DataFrame' object has no attribute 'as_matrix'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 2018-05-25
      • 2022-06-14
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多