【问题标题】:Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna'Python:Pandas Dataframe AttributeError:“numpy.ndarray”对象没有属性“fillna”
【发布时间】:2023-03-24 05:26:01
【问题描述】:

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

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 定义为什么?

标签: python pandas dataframe attributeerror


【解决方案1】:

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

print type(M)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的。我用过:y = [np.nan, np.nan, 2, 3, 4, 5, np.nan] y_temp = pd.DataFrame(y).fillna(1E-8)[0].values
    【解决方案3】:

    您的代码目前不完整,因此很难确定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. 您需要在代码中的其他位置将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)
      

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2020-11-29
      • 2020-10-06
      • 2018-01-25
      • 2016-06-29
      • 2020-03-25
      • 2013-12-07
      • 2017-10-16
      • 2020-02-23
      相关资源
      最近更新 更多