【问题标题】:AttributeError: 'int' object has no attribute 'dtype'AttributeError:“int”对象没有属性“dtype”
【发布时间】:2019-09-02 12:12:14
【问题描述】:

我正在尝试运行一个脚本来获取一些股票的数据。我试图获得的部分数据是流动性度量(称为 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!")

【问题讨论】:

  • 你能把有错误的那一行加进去吗?
  • @CeliusStingher 添加了!
  • @Leon numpy?这个错误通常在keras中发现。

标签: python numpy object int dtype


【解决方案1】:

[我会将此作为评论,但鉴于篇幅我不能]​​我觉得没有足够的信息可以帮助您解决问题,在你的位置,我会添加这个以确保我理解代码失败的原因,同时继续完成它的过程。这样,您就可以处理失败的文件并更正您的脚本,同时仍然获得结果。

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:
    try:
       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)
    except AttributeError:
          print(row[0])
          print('\n\n')
          print(row[1])
          continue

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!")

【讨论】:

  • 您还需要什么其他信息?我可以添加整个脚本。
  • 问题不是脚本,而是导致脚本失败的 csv 输出。我看不出脚本有什么问题(这就是它在前几次迭代中运行良好的原因)可能 csv 包含一些变形数据或类似的东西,导致脚本失败。
  • 您的“修复”有很大帮助,似乎当我现在运行脚本时,我只收到一次错误。在那 1 个错误之后,所有其他行都迭代得非常好......
  • 是的,但请记住,您正在跳过会产生错误的文件,这就是它起作用的原因。我添加了打印,因此当您从命令行执行它时,您可以可视化会产生错误的行输出,然后跳过它们。因此,您可以查看行并了解 AttributeError 背后的原因。
【解决方案2】:

所以根据回溯(幸好我们没有要求),错误发生在:

np.nanmean(illiq)

它试图调整返回值以匹配输入的dtype,可能是illiq。此时在nanmean(查看其代码)中,它已经对输入(在删除nan)、tot 和计数元素cnt 求和。它假设illiq 是一个数字numpy 数组(最好是float dtype,因为它必须处理float 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() 是从系列中获取数组的首选方式,尽管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 Series。这可以包括字符串和None 值。

【讨论】:

    【解决方案3】:

    简单的答案是您的数据不是 numpy 数据类型。这可能是因为该列不是完全数字的(即包含 None 或其他内容)。

    简短的解决方案:

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

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

    【讨论】:

    • 致任何在这篇文章中冒险的人:这是在另一位用户的报复性投反对票期间投反对票的。不要让这阻止你尝试这个。它对我有用!
    猜你喜欢
    • 2021-06-06
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2023-02-03
    • 2020-05-31
    • 2021-11-30
    • 2020-03-26
    相关资源
    最近更新 更多