numpy AttributeError:'int'对象没有属性'dtype'

dl5txlt9  于 2023-11-18  发布在  其他
关注(0)|答案(3)|浏览(211)

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

ohtdti5x

ohtdti5x1#

  • [我会把这个作为注解,但考虑到长度,我不能]* 我不觉得有足够的信息,我来帮助你解决这个问题,在你的地方,我会添加这个,以确保我理解为什么代码失败,并在同一时间继续完成它的过程。这样,你就可以工作的文件,失败和纠正你的脚本,同时仍然得到结果。
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!")

字符串

c6ubokkw

c6ubokkw2#

因此,根据追溯(谢天谢地,我们不必要求),错误发生在:

np.nanmean(illiq)

字符串
在这里,它试图调整返回值以匹配输入的dtype,可能是illiq。(查看其代码)它已对输入求和(在移除nan之后),tot,假设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_data是一个dataframe,输入是从单个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 Series。这可以包括字符串和None值。

gmxoilav

gmxoilav3#

简单的答案是,你的数据不是numpy数据类型。这可能是因为列不是完全数字的(即包含None或其他)。
简短的解决方案:

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

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

相关问题