【问题标题】:Using np.where() with conditional on count in time loop在时间循环中使用 np.where() 以计数为条件
【发布时间】:2020-01-12 16:42:22
【问题描述】:

我想使用 np.where() 指定一个新的 df 列 df['avg_gain'],其值来自其他两个 df 列之一,df['avg_gain_0']df['avg_gain_n'],使用的值由时间循环中的周期数('count' 变量)作为条件如下:

starttime = time.time()
count = 0 

def x(): 
    klines = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_15MINUTE)
    df = pd.DataFrame(klines)
    df.columns = ['timestart', 'open', 'high', 'low', 'close', 'timeend']

    ...

    df['change'] = df.close.astype(float).diff()
    df['gain'] = np.where(df['change'] > 0, df['change'], 0)

    df['avg_gain_0'] = df['gain'].rolling(window=6, center=False).mean()
    df['avg_gain_n'] = ((float(df['avg_gain'].iloc[-1]) * 5) + df['gain']) / 6
    df['avg_gain'] = np.where(count = 0, df['avg_gain_0'], df['avg_gain_n'])

while True:
    try:
        x()
        count += 1
        time.sleep(60.0 - ((time.time() - starttime) % 60.0))

用于df['gain']np.where() 函数运行良好,但我收到了一个

关键字参数后的位置参数

用于df['avg_gain']np.where() 函数出错。

我该如何解决?任何帮助表示赞赏。谢谢。

【问题讨论】:

  • df 中是否有 count 列? np.where() 的第一个参数需要类似于数组...
  • count=0 应该做什么?
  • count 变量在数据框之外,从 0 开始,每次运行 time/while 循环时加 1。

标签: python python-3.x pandas numpy


【解决方案1】:

您对 np.where 的调用包含 count = 0(带有 single “=”), 什么被解释为命名(关键字)参数。

np.where中,第一个参数是一个条件。 因此,您可能应该将此指令更改为:

np.where(count == 0, df['avg_gain_0'], df['avg_gain_n'])

(double "=").

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2021-10-03
    • 2022-01-03
    • 2021-05-15
    • 2018-03-21
    相关资源
    最近更新 更多