AttributeError:“Series”对象没有属性“sqrt”

2024-09-29 23:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理从EXCEL导入并转换为列表的一些数据集:

import pandas as pd
import numpy as np

datfrms = []
for i in xls.sheet_names:                                       
    df = pd.read_excel(xls, i)
    datfrms.append(df) 

data_a = []
data_b = []
data_c = []

for dfs in datfrms:
    data_a.append(dfs.loc[:,'data_a'])
    data_b.append(dfs.loc[:,'data_b'])
    data_c.append(dfs.loc[:,'data_c'])

然后,我想对数据进行一些计算,所以我决定将列表转换为numpy数组,并执行一些计算:

^{pr2}$

因此,ab和{}现在被定义为<class 'numpy.ndarray'>,形状为(13,),对应于我在上面导入的13张纸。每当我想访问第一个工作表中的数据时,我都会写,例如,data_a[0]。在

但是,如果要执行以下操作,则会出现一个错误:AttributeError: 'Series' object has no attribute 'sqrt'

d = np.sqrt(a / b)

如果我手动写入,不会产生错误:

d0 = np.sqrt(a[0] / b[0])
...
d12 = np.sqrt(a[12] / b[12])

{{cd8>使用函数。。。d12现在是{},而{}和{}都是{}。在

  • 我做错什么了?在
  • 为什么不允许我执行一个简单的平方根运算?在

我希望我可以添加数据,但我无法通过在Python中生成合成数据来重新创建数据格式,我怀疑这可能是问题的核心(即,我在数据格式方面做了一些错误)。在

user32185分别请求了a[0]和{}的输出:

0     0.883871
1     0.885714
2     0.879378
3     0.865668
4     0.866014
5     0.860657
6     0.866071
7     0.884389
8     0.892339
9     0.892512
10    0.841590
11    0.841014
12    0.882200
13    0.857546
14    0.850576
15    0.853975
16    0.838710
dtype: float64

以及

0     3.701151
1     3.701938
2     3.700758
3     3.690926
4     3.685027
5     3.688959
6     3.712556
7     3.786099
8     3.888745
9     3.956389
10    3.799078
11    3.799078
12    3.778627
13    3.669295
14    3.638620
15    3.606371
16    3.547379
Name: b, dtype: float64

Tags: 数据importnumpy列表fordataas错误
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:42

您的ab是对象数据类型数组。你说呢

with shape (13,), corresponding to the 13 sheets I imported above

错误表明数组的元素是串联的。在

type(a[0])   # what is it?

对象数据类型数组上的数学命中或错误:

^{pr2}$

它将数学委托给对象的方法。+和/工作是因为定义了相应的方法(对于我的示例中的float,在您的示例中是Series)。但是大多数类没有定义sqrt方法,因此失败了。在


如果您的初始数据帧都具有相同的行数,则由它们生成的数组a将是2d numeric dtype。你可以在他们身上做所有的数学运算。但由于数据帧不同,Series生成的数组是Series的对象dtype数组。在

In [201]: df1 = pd.DataFrame(np.arange(12).reshape(4,3))

来自相同大小序列的二维数字数组:

In [204]: x=np.array([df1.loc[:,0], df1.loc[:,1]])
In [205]: x
Out[205]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10]])
In [206]: x.dtype
Out[206]: dtype('int64')

具有不同大小系列的对象数组:

In [207]: df2 = pd.DataFrame(np.arange(15).reshape(5,3))
In [208]: x=np.array([df1.loc[:,0], df2.loc[:,0]])
In [210]: type(x[0])
Out[210]: pandas.core.series.Series

对对象数组求和是有效的,但请注意数据类型

In [212]: x+x
Out[212]: 
array([0     0
1     6
2    12
3    18
Name: 0, dtype: int64,
       0     0
1     6
2    12
3    18
4    24
Name: 0, dtype: int64], dtype=object)

In [213]: np.sqrt(x)
...
AttributeError: 'Series' object has no attribute 'sqrt'

相关问题 更多 >

    热门问题