AttributeError:“ int”对象没有属性“ dtype”

时间:2019-09-02 12:12:14

标签: python numpy object int dtype

我正在尝试运行脚本以获取许多股票的数据。我尝试获取的部分数据是流动性度量(称为Amihud流动性度量)。我使脚本自动化,但是在运行自动化脚本时,大约15到20个成功返回后,我得到一个错误。 我该如何解决这个问题?

File "script.py", line 23, in <module>
return_data = function.get_data(row[1], row[0])
File "C:\Users\leon_\function.py", line 39, in get_data
print(np.nanmean(illiq))
File "D:\Anaconda3\lib\site-packages\numpy\lib\nanfunctions.py", line 916, in nanmean
avg = _divide_by_count(tot, cnt, out=out)
File "D:\Anaconda3\lib\site-packages\numpy\lib\nanfunctions.py", line 190, in _divide_by_count
return a.dtype.type(a / b)
AttributeError: 'int' object has no attribute 'dtype'

处理流动性不足的代码部分:

  # Amihuds Liquidity measure
    liquidity_pricing_date = date_1 + datetime.timedelta(days=-20)
    liquidity_pricing_date2 = date_1 + datetime.timedelta(days=-120)
    stock_data = quandl.get(stock_ticker, start_date=liquidity_pricing_date2, end_date=liquidity_pricing_date)
    p = np.array(stock_data['Adj. Close'])
    returns = np.array(stock_data['Adj. Close'].pct_change())
    dollar_volume = np.array(stock_data['Volume'] * p)
    illiq = (np.divide(returns, dollar_volume))
    print(np.nanmean(illiq))
    illiquidity_measure = np.nanmean(illiq, dtype=float) * (10 ** 6)  # multiply by 10^6 for expositional purposes
    return [stock_vola, stock_price_average, illiquidity_measure]

有人知道如何解决这个问题吗?

编辑:这是脚本文件

# Open File Dialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

# Load Spreadsheet data
f = open(file_path)

csv_f = csv.reader(f)
next(csv_f)

result_data = []

# Iterate
for row in csv_f:
    return_data = function.get_data(row[1], row[0])
    if len(return_data) != 0:
        # print(return_data)
        result_data_loc = [row[1], row[0]]
        result_data_loc.extend(return_data)
        result_data.append(result_data_loc)

if result_data is not None:
    with open('resuls.csv', mode='w', newline='') as result_file:
        csv_writer = csv.writer(result_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for result in result_data:
            # print(result)
            csv_writer.writerow(result)
else:
    print("No results found!")

3 个答案:

答案 0 :(得分:0)

[我将其作为注释,但考虑到我无法提供的长度] ,我觉得没有足够的信息可以帮助您解决问题,在您的位置上,我将添加此内容以确保我理解为什么代码失败,并同时继续执行该过程以完成它。这样,您就可以处理失败的文件并更正脚本,同时仍然获得结果。

{
    "name": "vista",
    "version": "0.0.1",
    "description": "sample chaincode",
    "engines": {
        "node": ">=8.4.0",
        "npm": ">=5.3.0"
    },
    "scripts": {
        "start": "node vista.js"
    },
    "engine-strict": true,
    "license": "Apache-2.0",
    "dependencies": {
        "fabric-shim": "1.2.0"
    }
} 

答案 1 :(得分:0)

因此,根据追溯(很遗憾,我们不必要求这样做),错误发生在:

np.nanmean(illiq)

尝试调整返回值以匹配输入的dtype,可能是illiq。此时,在nanmean中(查看其代码),已对输入(除去nan之后),tot和计数元素cnt进行求和。假设illiq是一个数字numpy数组(最好是float dtype,因为它必须处理浮点数np.nan)。

因此它在大多数情况下都有效,但是在某些情况下会失败。在这些情况下,illiq有什么不同?

p = np.array(stock_data['Adj. Close'])
returns = np.array(stock_data['Adj. Close'].pct_change())
dollar_volume = np.array(stock_data['Volume'] * p)
illiq = (np.divide(returns, dollar_volume))

看起来stock_datadataframe,输入是从单个series派生的数组。我相信stock_data[name].to_num()是从Series获得数组的首选方式,尽管np.array(...)在大多数情况下都可以工作。也使用了stock_data[name].values

我建议在此调用之前对illiq进行一些测试。至少检查shapedtype。尝试找出问题案例中的不同之处。

这是一个简单的情况,会产生此错误:

In [117]: np.nanmean(np.array([0,3],object))                                                                 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-117-26ab42d92ec9> in <module>
----> 1 np.nanmean(np.array([0,3],object))

<__array_function__ internals> in nanmean(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/lib/nanfunctions.py in nanmean(a, axis, dtype, out, keepdims)
    949     cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)
    950     tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
--> 951     avg = _divide_by_count(tot, cnt, out=out)
    952 
    953     isbad = (cnt == 0)

/usr/local/lib/python3.6/dist-packages/numpy/lib/nanfunctions.py in _divide_by_count(a, b, out)
    216         else:
    217             if out is None:
--> 218                 return a.dtype.type(a / b)
    219             else:
    220                 # This is questionable, but currently a numpy scalar can

AttributeError: 'int' object has no attribute 'dtype'

pandas通常在一个或多个值不是有效数字时创建对象dtype系列。其中可以包含字符串和None值。

答案 2 :(得分:-1)

简单的答案是您的数据不是numpy数据类型。这可能是因为该列不是全数字的(即,不包含任何内容)。

简短的解决方案:

print(np.nanmean(pd.to_numeric(illiq)))

解决此问题的最快方法是将数据强制转换为numpy喜欢的数字类型。这可以通过熊猫的to_numeric方法来完成。