【问题标题】:Find float in dataFrame using a For loop使用 For 循环在 dataFrame 中查找浮点数
【发布时间】:2017-04-14 07:24:39
【问题描述】:

我有一个函数,我将遍历它以找到一个浮点数的第一个实例,然后打印“我们达到了利润”。在下面的情况下,我想从 WAP 列中找到 8.49 并停止查找。我收到错误消息: 对于利润_价格中的 x: TypeError: 'numpy.float64' 对象不可迭代

profit_Price = round((Wap_price * 0.020) + Wap_price,2)

def profit_stop(x):

    for x in profit_Price:
        if x == 8.49:
            print('we hit profit')
    else:
        return x

#calls the above function 'profit_stop'
df['WAP'].apply(profit_stop)

【问题讨论】:

  • 我不确定您要做什么。 apply 分别运行在每个元素上给出的函数,即 - 对于 df['WAP'] 中的每个数字 num,它将运行 profit_stop(num)。中间没有办法停止apply(除了提升Exception
  • 那么我应该如何将逻辑测试应用于数据框中的 WAP 列。我需要从列中创建一个列表然后遍历它吗?
  • pandas.Series 上的任何逻辑操作都是元素操作。试试df['WAP'] == 8.49 看看会发生什么。那就试试df[df['WAP'] == 8.49]
  • 虽然你最好不要使用df[np.isclose(df['WAP'], 8.49)](因为浮点比较并不总是100%准确)
  • 我看到一个会返回 True/False 和行号。第二个返回 WAP 包含 8.49 的整行。但是,当我使用 var 名称 Profit_Price 时,我得到“空 DataFrame”。利润价格是 。我试图在 WAP 列中找到第一行有我的 profit_Price。我还希望我的 WAP 列不会总是包含我的 Profit_Price,我将在 WAP 列中搜索低于我的 profit_Price 的止损值。如果我们达到了 profit_Price 显示发生的第一行。如果我们没有达到 Profit_Price,显示我们达到 stop_loss 的行。

标签: python pandas numpy for-loop


【解决方案1】:

如果您的目的是比较,则不必担心停止(除非您的 DataFrame 真的很大)。 pandas 依赖于 numpy 比较,这非常有效,并且比 Python for 循环运行得更快。

运行df['WAP'] == 8.49np.close(df['WAP'], 8.49) 将为series 中的每个元素返回一个布尔数组(True/False)。您可以使用它来过滤您的 series 以获得想要的值:

df[np.close(df['WAP'], 8.49)]

这将返回DataFrame,其中仅包含 WAP 为 8.49 的行。

【讨论】:

    【解决方案2】:
    wap = df['WAP']
    wap = [float(x) for x in wap] #    lets make sure type is correct
    
    
    for x in wap:
        while x < 8.49:
           print(x)
           break
        else:
           print('we hit it')
           break
    

    这应该在接近 8.49 时停止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 2019-12-14
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多