Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna'

Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna'

由于我正在创建数据框,所以我不明白为什么会出现数组错误。

M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
M2 = np.maximum(-1, (M - 3).fillna(0) / 2.)  # scale to -1..+1  (treat "0" scores as "1" scores)
M2.head(2)

AttributeError: 'numpy.ndarray' object has no attribute 'fillna'

(M - 3) 被解释为 numpy.ndarray。这意味着 M 在某处被定义为 numpy.ndarray。通过 运行:

进行测试
print type(M)

您的代码目前不完整,因此很难确定 M 导致错误的原因。可能有几个原因:

  1. 你打错了 (M - 3) 应该是 (M2 - 3)

    M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
    M2 = np.maximum(-1, (M2 - 3).fillna(0) / 2.)  # scale to -1..+1  (treat "0" scores as "1" scores)
    M2.head(2)
    
  2. 您需要 define/convert M 作为 pandas.DataFrame 在代码的其他地方

    # With out seeing this part of the code, no one can really help you
    M = pd.DataFrame(...)
    # ...
    # ...
    M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
    M2 = np.maximum(-1, (M - 3).fillna(0) / 2.)  # scale to -1..+1  (treat "0" scores as "1" scores)
    M2.head(2)
    
  3. 您可以在使用前将其转换为 pandas.DataFrame

    M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
    M2 = np.maximum(-1, (pd.DataFrame(M) - 3).fillna(0) / 2.)  # scale to -1..+1  (treat "0" scores as "1" scores)
    M2.head(2)
    

您正在对 numpy 数组调用 .fillna() 方法。 numpy 数组没有定义该方法。

您或许可以将 numpy 数组转换为 pandas.DataFrame,然后应用 .fillna() 方法。