根据另一列的值计算熊猫数据框索引差异

时间:2019-03-23 15:21:40

标签: python pandas

我试图找出如何计算当前行与某列具有特定值的行的索引差。

我有一个数据框:

import pandas as pd

# pandas settings
pd.set_option('display.max_columns', 320)
pd.set_option('display.max_rows', 1320)
pd.set_option('display.width', 320)

df = pd.read_csv('https://www.dropbox.com/s/hy94jp4d7qwmv04/eurusd_df1.csv?dl=1')

所以我想计算 candle = Candle-20

例如,如果当前行是583185,蜡烛值是119,那么我们感兴趣的蜡烛是99。我们需要弄清楚 current_index-index(其中Candle = 99第一次出现)

我希望我能说清楚,干杯=)

编辑: 好的,我在上面做了非常糟糕的解释。.

我相信我实际上已经很接近自己解决这个问题了。看看:

x = df.index[df.candle == df.candle - 20][0]
df['test'] = df.bid.rolling(int(x)).mean()

因此,“测试”列应为df.bid的最后X行的mean()值,其中X是当前df.candle与返回20根蜡烛的行之间的行数(第一次迭代,所以[0 ](有许多行具有相同的蜡烛值)

但是上面的代码给出了一个错误:

IndexError:索引0超出了尺寸为0的轴0的范围

1 个答案:

答案 0 :(得分:0)

这里是实现此目的的方法:

# Generate example data
np.random.seed(0)
df = pd.Series(np.round(np.random.rand(1000000)*1000), dtype=int, name='candle').to_frame()

# Compute row index where df.candle is 20 less than candle_value at current_index
current_index = 583185
candle_value = df.loc[current_index, 'candle'] # = 119 in your df
index = df.index[df.candle == candle_value - 20][0]
print(index)
835

编辑:要计算索引差,只需减去它们:

X = current_index - index
print(X)
582350

然后您可以计算公式:

b = 0.015 * TP.rolling(X).std()