【问题标题】:iterating over each row in pandas to evaluate condition遍历 pandas 中的每一行以评估条件
【发布时间】:2021-10-15 11:11:27
【问题描述】:

我有以下代码

import pandas as pd
from pandas_datareader import data as web
import numpy as np
import math

data = web.DataReader('goog', 'yahoo')
df['lifetime'] = data['High'].asfreq('D').rolling(window=999999, min_periods=1).max() #To check if it is a lifetime high

如果熊猫中每一行的df['High'] 接近它的df['lifetime'],我如何比较它以便我得到一个布尔值(最好是1 和0):

data['isclose'] = math.isclose(data['High'], data['lifetime'], rel_tol = 0.003)

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用np.where()

    import numpy as np
    import math
    
    data['isclose'] = np.where(math.isclose(data['High'], data['lifetime'], rel_tol = 0.003), 1, 0)
    

    【讨论】:

      【解决方案2】:

      你也可以使用pandas'apply()函数:

      import math
      
      from pandas_datareader import data as web
      
      data = web.DataReader("goog", "yahoo")
      
      data["lifetime"] = data["High"].asfreq("D").rolling(window=999999, min_periods=1).max()
      
      data["isclose"] = data.apply(
          lambda row: 1 if math.isclose(row["High"], row["lifetime"], rel_tol=0.003) else 0,
          axis=1,
      )
      
      print(data)
      

      但是yudhiesh's solution 使用 np.where() 更快。 另见:Why is np.where faster than pd.apply

      【讨论】:

        猜你喜欢
        • 2019-02-02
        • 1970-01-01
        • 2016-02-07
        • 1970-01-01
        • 2021-06-03
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        • 2019-06-12
        相关资源
        最近更新 更多