遍历 pandas 数据框并应用 if else 函数

looping through a pandas dataframe and applying an if esle function

我正在尝试使用 python 构建一个简单的回测器,回测器通过在特定时间内比较 2 个值来工作,因为(在时间 x 检查是否 indicator_value > ohlc_value : order_type = 1;否则订单类型将为 = 0)

data = {'time':[0, 1, 2, 3, 4, 5], 'ohlc':[1.1, 1.2, 1.3, 1.4, 1.5,1.66], 'indicator':[1.05, 1.22, 1.4, 1.55, 1.6,1.77]}
df = pd.DataFrame(data)

如何设置这些值?

if data['ohlc'] > data['indicator']:
      data['order_type'] = 1
else:
      data['order_type'] = 0

我知道我不能像那样循环数据帧。

给你:

df['order_type'] = (df['ohlc'] > df['indicator']).astype(int)
print(df)

输出:

   time  ohlc  indicator  order_type
0     0  1.10       1.05           1
1     1  1.20       1.22           0
2     2  1.30       1.40           0
3     3  1.40       1.55           0
4     4  1.50       1.60           0
5     5  1.66       1.77           0

如果您要根据不同的条件分配自定义值,这里有一种方法(默认为 0):

import numpy as np
conditions = [df['ohlc'] > df['indicator']]
choices = [-1]
df['order_type'] = np.select(conditions, choices)
print(df)

输出:

   time  ohlc  indicator  order_type
0     0  1.10       1.05          -1
1     1  1.20       1.22           0
2     2  1.30       1.40           0
3     3  1.40       1.55           0
4     4  1.50       1.60           0
5     5  1.66       1.77           0

你也可以试试这个

def fun(row):
    return 1 if row['ohlc']>row['indicator'] else 0 

df['order_type']=df.apply(fun,axis=1)
df