首页 > 解决方案 > 在 Pandas 中执行此操作的更好方法?

问题描述

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

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

#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))

标签: pythonpandasdataframestock

解决方案


您可以直接这样做:

(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,其中 1 if ais greater 和 9 if bis greater :

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

推荐阅读