Python 如何修复 AttributeError: 'Series' 对象没有属性 'to_numpy'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54650748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix AttributeError: 'Series' object has no attribute 'to_numpy'
提问by Nguyen Thuan
My output:
我的输出:
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)
This is my code with pandas library as pd. When I run in Google Colab I get the following error:
这是我使用 Pandas 库作为 pd 的代码。当我在 Google Colab 中运行时,出现以下错误:
AttributeError: 'Series' object has no attribute 'to_numpy'
回答by Javide
Check the version of your pandas library:
检查您的熊猫库的版本:
import pandas
print(pandas.__version__)
If your version is less than 0.24.1:
如果您的版本低于 0.24.1:
pip install --upgrade pandas
回答by Mike T
If you need your code to work with all versions of pandas, here's a simple way to convert a Series into a NumPy array:
如果您需要您的代码与所有版本的 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]
On an advanced note, if your Series has missing values (as NaN values), these can be converted to a masked array:
在高级说明中,如果您的系列缺少值(作为 NaN 值),则可以将这些值转换为掩码数组:
s = pd.Series([1.1, np.nan])
a = np.ma.masked_invalid(s)
print(a) # [1.1 --]