You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算25日高点距今天数遇TypeError,如何将NumPy数组转为int?

问题描述

我需要找到特定float值的索引,最初运行以下代码成功实现需求:

RELIANCE = pdr.get_data_yahoo('RELIANCE.NS', start='2023-02-01', end='2023-12-06')
RELIANCE.reset_index(inplace=True)
close_REL = RELIANCE['Close'].values
first_25DH = max(close_REL[25-25:25+1])
first_ds25dh = 25-int(np.where(RELIANCE['Close'][25-25:25+1] == first_25DH)[0])

但尝试用for循环实现相同功能时出现错误,所用for循环代码如下:

# 创建25日高点列
high_25D = []
for j in range(RELIANCE.shape[0]):
    if j < 25:
        high_25D.append(0)
    else:
        high_25D_j = max(close_REL[j-25:j+1])
        high_25D.append(high_25D_j)
RELIANCE['25D_high'] = high_25D

# 计算25日高点距今天数
days_since_25DH = []
for j in range(RELIANCE.shape[0]):
    if j < 25:
        days_since_25DH.append(0)
    else:
        index_of_high_j = int(np.where(RELIANCE['Close'] == high_25D[j])[0])
        days_since_j = j - index_of_high_j
        days_since_25DH.append(days_since_j)

RELIANCE['Days since 25 day high'] = days_since_25DH

报错信息如下:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [163], line 6
      4     days_since_25DH.append(0)
      5 else:
----> 6     index_of_high_j = int(np.where(RELIANCE['Close'] == high_25D[j])[0])
      7     days_since_j = j - index_of_high_j
      8     days_since_25DH.append(days_since_j)

TypeError: only size-1 arrays can be converted to Python scalars

去掉int()后代码可运行,但25行之后的元素为numpy.ndarray对象,我希望这些元素是int类型,请问该如何解决?


解决方案

问题核心是你在整个Close列中查找高点索引,而不是限定在当前的25日窗口范围内,这会导致np.where返回包含多个元素的数组,无法直接转成int。

修复后的循环代码

# 创建25日高点列
high_25D = []
for j in range(RELIANCE.shape[0]):
    if j < 25:
        high_25D.append(0)
    else:
        # 锁定当前25日窗口
        window = close_REL[j-25:j+1]
        high_25D_j = max(window)
        high_25D.append(high_25D_j)
RELIANCE['25D_high'] = high_25D

# 计算25日高点距今天数
days_since_25DH = []
for j in range(RELIANCE.shape[0]):
    if j < 25:
        days_since_25DH.append(0)
    else:
        # 仅在当前窗口内查找高点位置
        window = close_REL[j-25:j+1]
        high_val = high_25D[j]
        # 取窗口内第一个出现高点的位置(和原代码逻辑一致)
        idx_in_window = np.where(window == high_val)[0][0]
        # 转换为整个DataFrame的索引
        index_of_high_j = (j - 25) + idx_in_window
        # 计算天数差并转成int
        days_since_j = int(j - index_of_high_j)
        days_since_25DH.append(days_since_j)

RELIANCE['Days since 25 day high'] = days_since_25DH

更高效的向量化实现

用Pandas滚动窗口替代循环,速度更快:

import pandas as pd
import numpy as np
import pandas_datareader as pdr

RELIANCE = pdr.get_data_yahoo('RELIANCE.NS', start='2023-02-01', end='2023-12-06')
RELIANCE.reset_index(inplace=True)

# 计算25日滚动高点,前25行设为0
RELIANCE['25D_high'] = RELIANCE['Close'].rolling(window=26, min_periods=1).max()
RELIANCE.loc[:24, '25D_high'] = 0

# 定义滚动窗口内计算天数差的函数
def calc_days_since_high(window):
    if len(window) < 26:
        return 0
    high_val = window.max()
    # 取窗口内最后一个高点的位置(如需第一个改[0])
    idx = np.where(window == high_val)[0][-1]
    return len(window)-1 - idx

# 应用滚动计算并转成int类型
RELIANCE['Days since 25 day high'] = RELIANCE['Close'].rolling(window=26, min_periods=1).apply(calc_days_since_high, raw=True).astype(int)
RELIANCE.loc[:24, 'Days since 25 day high'] = 0

内容的提问来源于stack exchange,提问作者Digant Shetkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:02:12