在Dataframe中的两个数字之间划分

时间:2016-12-03 05:04:20

标签: pandas dataframe integer-division

当我触发来自另一列的信号时,我试图计算一列中2个数字之间的百分比变化。

触发器可以在np.where()找到,但我遇到的问题是百分比变化。 .pct_change不起作用,因为如果您.pct_change(-5)获得16.03/20.35,我希望数字与20.35/16.03相反。见下表。我已尝试从np.where中的索引返回数组并将其从“关闭”列添加到.iloc,但它说我无法使用该数组来获取.iloc位置。任何人都可以帮我解决这个问题。谢谢。

IdxNum |  Close |  Signal (1s)
==============================      
0          21.45        0       
1          21.41        0       
2          21.52        0       
3          21.71        0       
4          20.8         0       
5          20.35        0       
6          20.44        0       
7          16.99        0       
8          17.02        0       
9          16.69        0       
10         16.03    1<<  26.9% <<< 20.35/16.03-1 (df.Close[5]/df.Close[10]-1)

11         15.67        0           
12         15.6         0       

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码块:

#Create DataFrame
df = pd.DataFrame({'IdxNum':range(13),
                   'Close':[21.45,21.41,21.52,21.71,20.8,20.35,20.44,16.99,17.02,16.69,16.03,15.67,15.6],
                  'Signal':[0] * 13})
df.ix[10,'Signal']=1

#Create a function that calculates the reqd diff
def cal_diff(row):
    if(row['Signal']==1):
        signal_index = int(row['IdxNum'])
        row['diff'] = df.Close[signal_index-5]/df.Close[signal_index]-1
    return row

#Create a column and apply that difference
df['diff'] = 0
df = df.apply(lambda x:cal_diff(x),axis=1)

如果您没有 IdxNum 列,则可以使用索引计算差异

#Create DataFrame
df = pd.DataFrame({
                   'Close':[21.45,21.41,21.52,21.71,20.8,20.35,20.44,16.99,17.02,16.69,16.03,15.67,15.6],
                  'Signal':[0] * 13})
df.ix[10,'Signal']=1

#Calculate the reqd difference
df['diff'] = 0
signal_index = df[df['Signal']==1].index[0]
df.ix[signal_index,'diff'] =  df.Close[signal_index-5]/df.Close[signal_index]-1