IF条件由一对条件组成

时间:2015-12-03 14:28:22

标签: python pandas dataframe

我有这个循环检查以下条件。对于i的每次迭代,需要获得m1, m2, m3, m4 and m5的值。 if语句是否需要像这样(通过“对”)进行检查,还是有更聪明/更快的方法呢?

for i in range(len(df.index)):

    if      df.ix[i, 'ema4'] >= df.ix[i, 'ema9']:
            m1 = 1
    elif    df.ix[i, 'ema4'] < df.ix[i, 'ema9']:
            m1 = -1

    if      df.ix[i, 'ema9'] >= df.ix[i, 'ema20']:
            m2 = 1            
    elif    df.ix[i, 'ema9'] < df.ix[i, 'ema20']:
            m2 = -1

    if      df.ix[i, 'ema20'] >= df.ix[i, 'ema48']:
            m3 = 1
    elif    df.ix[i, 'ema20'] < df.ix[i, 'ema48']:
            m3 = -1        

    if      df.ix[i, 'ema48'] >= df.ix[i, 'ema80']:
            m4 = 1
    elif    df.ix[i, 'ema48'] < df.ix[i, 'ema80']:
            m4 = -1  

    if      df.ix[i, 'ema80'] >= df.ix[i, 'ema100']:
            m5 = 1
    elif    df.ix[i, 'ema80'] < df.ix[i, 'ema100']:
            m5 = -1 

    df.ix[i,'test'] = (m1 + m2 + m3 + m4 + m5)   

3 个答案:

答案 0 :(得分:4)

为了简化代码,您可以将变量初始化为默认值并使用一堆if s:

m1 = m2 = m3 = m4 = m5 = -1

for i in range(len(df.index)):
    if df.ix[i, 'ema4'] >= df.ix[i, 'ema9']:
        m1 = 1
    ...

答案 1 :(得分:1)

你可以使用2个循环,一个是@eugene y提到的,稍微修改了列表,另一个是你的列:

df_size = len(df.index)
m = [-1] * df_size 
col_names = ['ema4', 'ema9', 'ema20', 'ema48', 'ema80']

for i in range(df_size ):
     for col_name in col_names:
          if df.ix[i, col_name] >= df.ix[i, col_name ]:
               m[i] = 1


df.ix[i,'test'] = sum(m)

答案 2 :(得分:0)

就像评论说的那样只使用其他:

for i in range(len(df.index)):
    if df.ix[i, 'ema4'] >= df.ix[i, 'ema9']:
        m1 = 1
    else:
        m1 = -1

或者您可以预设并执行if:

    m1 = -1
    if df.ix[i, 'ema4'] >= df.ix[i, 'ema9']:
        m1 = 1

重复所有ifs