【问题标题】:Better Way to do this in Pandas?在 Pandas 中执行此操作的更好方法?
【发布时间】:2020-04-24 22:41:37
【问题描述】:

我只是在寻求一些关于如何更好地做到这一点的指导。我只是在做一些基础研究来比较周一的开盘价和低点。代码代码返回两个列表,一个带有回报(周一收盘 - 开盘/周一开盘)和一个只有 1 和 0 的列表,以反映回报是正数还是负数。

请看一下,因为我确信在 pandas 中有更好的方法,但我只是不知道如何。

#Monday only
m_list = [] #results list
h_list = [] #hit list (close-low > 0)
n=0 #counter variable
for t in history.index:
    if datetime.datetime.weekday(t[1]) == 1: #t[1] is the timestamp in multi index (if timestemp is a Monday)
    x = history.ix[n]['open']-history.ix[n]['low']
    m_list.append((history.ix[n]['open']-history.ix[n]['low'])/history.ix[n]['open'])
    if x > 0:
        h_list.append(1)
    else:
        h_list.append(0)
    n += 1 #add to index counter
else:
    n += 1  #add to index counter 

print("Mean: ", mean(m_list), "Max: ", max(m_list),"Min: ", 
  min(m_list), "Hit Rate: ", sum(h_list)/len(h_list))

【问题讨论】:

    标签: python pandas dataframe stock


    【解决方案1】:

    你可以直接做到这一点:

    (history['open']-history['low'])>0

    这将为您提供true 用于open 更大的行和flase 其中low 更大的行。

    如果你想要1,0,你可以将上面的语句乘以1。

    ((history['open']-history['low'])>0)*1

    示例

    import numpy as np 
    import pandas as pd
    
    df = pd.DataFrame({'a':np.random.random(10),
                      'b':np.random.random(10)})
    

    打印数据框:

    print(df)
    
        a   b
    0   0.675916    0.796333
    1   0.044582    0.352145
    2   0.053654    0.784185
    3   0.189674    0.036730
    4   0.329166    0.021920
    5   0.163660    0.331089
    6   0.042633    0.517015
    7   0.544534    0.770192
    8   0.542793    0.379054
    9   0.712132    0.712552
    

    创建一个新列compare,如果a 更大,则为1,如果b 更大,则为9:

    df['compare'] = (df['a']-df['b']>0)*1
    

    这将添加新列compare:

        a   b   compare
    0   0.675916    0.796333    0
    1   0.044582    0.352145    0
    2   0.053654    0.784185    0
    3   0.189674    0.036730    1
    4   0.329166    0.021920    1
    5   0.163660    0.331089    0
    6   0.042633    0.517015    0
    7   0.544534    0.770192    0
    8   0.542793    0.379054    1
    9   0.712132    0.712552    0
    

    【讨论】:

    • 谢谢,那么这样做会更好然后提取星期一的数据吗?
    • 在 pandas 中使用内置的列处理方式比在代码中逐行处理要好且容易。这至少是清晰易懂的,也许也更快。如上所示,您可以轻松添加新列并对列进行操作。
    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多