【问题标题】:How to fix AttributeError: 'Series' object has no attribute 'to_numpy'如何修复 AttributeError:“系列”对象没有属性“to_numpy”
【发布时间】:2019-07-06 03:20:23
【问题描述】:

我的输出:

def load_data(self):
    """
    Load data from list of paths
    :return: 3D-array X and 2D-array y
    """
    X = None
    y = None
    df = pd.read_excel('data/Data.xlsx', header=None)
    for i in range(len(df.columns)):
        sentences_ = df[i].to_numpy().tolist()
        label_vec = [0.0 for _ in range(0, self.n_class)]
        label_vec[i] = 1.0
        labels_ = [label_vec for _ in range(0, len(sentences_))]
        if X is None:
            X = sentences_
            y = labels_
        else:
            X += sentences_
            y += labels_
    X, max_length = self.tokenize_sentences(X)
    X = self.word_embed_sentences(X, max_length=self.max_length)
    return np.array(X), np.array(y)

这是我将 pandas 库作为 pd 的代码。当我在 Google Colab 中运行时,我收到以下错误:

AttributeError: 'Series' object has no attribute 'to_numpy'

【问题讨论】:

  • 请添加错误输出以获取更多详细信息,例如错误发生在哪一行?
  • 你用的是什么熊猫版本?你可以试试df[i].values.tolist() ?
  • 句子错误_ = df[i].to_numpy().tolist()
  • 我用的是熊猫 0.24.1
  • to_numpy() 是一种新方法,我会在 colab 中仔细检查您的 Pandas 版本 - 也许它不匹配

标签: python pandas attributeerror


【解决方案1】:

检查你的熊猫库的版本:

import pandas
print(pandas.__version__)

如果您的版本低于 0.24.1:

pip install --upgrade pandas

【讨论】:

    【解决方案2】:

    如果您需要您的代码与所有版本的 pandas 一起使用,这里有一种将 Series 转换为 NumPy 数组的简单方法:

    import pandas as pd
    import numpy as np
    
    s = pd.Series([1.1, 2.3])
    a = np.array(s)
    print(a)  # [1.1 2.3]
    

    在高级说明中,如果您的 Series 有缺失值(作为 NaN 值),这些可以转换为掩码数组:

    s = pd.Series([1.1, np.nan])
    a = np.ma.masked_invalid(s)
    print(a)  # [1.1 --]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 2019-12-30
      • 2021-04-20
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多