python - 根据另一列的值计算熊猫数据框索引差异
问题描述
我试图弄清楚如何计算当前行的索引与 WHERE 某列具有特定值的行的差异。
IE
我有一个数据框:
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')
所以我想计算后面有多少个索引是蜡烛=蜡烛20的行
例如,如果当前行是 583185,蜡烛值是 119,那么我们感兴趣的蜡烛是 99。我们需要计算 current_index - index(其中蜡烛 = 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
解决方案
这是实现此目的的方法:
# 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()
推荐阅读
- android - Android:列表离开屏幕时的RecyclerView布局问题
- azure - 查询 Azure App Services 是否有备份设置
- c# - C# 找不到带有 GraphQL 的包
- javascript - Chart.js:如何设置图表的最小高度但仍保持纵横比?
- c++ - use of flow operators on objects
- javascript - 我需要帮助更新此数组状态以显示为表数据
- type-conversion - 如何在 AutoHotkey 中将变量转换为布尔值?
- postgresql - 空闲事务 mybatis jboss 6.4 postgres 9.6
- python - 使用 Python sqlparse 获取查询树/层次结构
- excel - Excel 连接到 SQL Server:连接到不同 SQL 驱动程序的区别