python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueError : cannot join with no overlapping index names

标签 python pandas dataframe time-series

我的目标:

我有两个时间序列数据帧,一个时间间隔为1m,另一个时间间隔为5m。 5m 数据帧是 1m 数据的重采样版本。我正在做的是使用 vectorbt 库计算一组对应于 5m df 的 RSI 值,然后使用 df.align 将这些值对齐并广播到 1m df。

问题:

尝试逐行执行此操作时,效果非常好。最终结果如下所示:

enter image description here

但是,在函数下应用它时,它返回以下错误,同时具有重叠的索引名称:

ValueError: cannot join with no overlapping index names

完整代码如下:

import vectorbt as vbt
import numpy as np
import pandas as pd
import datetime

end_date = datetime.datetime.now()
start_date = end_date - datetime.timedelta(days=3)

btc_price = vbt.YFData.download('BTC-USD',
                                interval='1m',
                                start=start_date,
                                end=end_date,
                                missing_index='drop').get('Close')


def custom_indicator(close, rsi_window=14, ma_window=50):
    close_5m = close.resample('5T').last()
    rsi = vbt.RSI.run(close_5m, window=rsi_window).rsi
    rsi, _ = rsi.align(close, broadcast_axis=0, method='ffill')
    print(rsi) #to check
    print(close) #to check
    return

#setting up indicator factory
ind = vbt.IndicatorFactory(
    class_name='Combination',
    short_name='comb',
    input_names=['close'],
    param_names=['rsi_window', 'ma_window'],
    output_names=['value']).from_apply_func(custom_indicator,
                                            rsi_window=14,
                                             ma_window=50,
                                            keep_pd=True)
    
res = ind.run(btc_price, rsi_window=21, ma_window=50)


print(res)

感谢您花时间阅读本文。任何帮助将不胜感激!

最佳答案

如果你检查了 , rsi 和 close 的列

print('close is', close.columns)
print('rsi is', rsi.columns)

你会发现

rsi is MultiIndex([(14, 'Close')],
           names=['rsi_window', None])
close is Index(['Close'], dtype='object')

因为它有两个索引,所以应该删除一个,所以可以通过下面的代码来完成

rsi.columns = rsi.columns.droplevel()

删除一级索引,以便对齐,

关于python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueError : cannot join with no overlapping index names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71895587/

相关文章:

python - 为什么我的 Tensorflow 神经网络在开始训练后表现得如此缓慢?

python - 寻找最大派系并删除节点?

scala - 在读取 CSV 时,最后一列在 Spark、Scala 中显示为 Null

pandas - 类型错误 : unhashable type: 'numpy.ndarray' - How to get data from data frame by querying radius from ball tree?

python - 我可以在 Golang 中加载经过 Python 训练的分类器吗?

python - 如何获取 groupby 的最大计数(最常见的项目)

python - 如何计算按两列分组的数据框中的百分比

python - 循环具有不同名称的列

python - 在python pandas数据框中修复City,State,Zip数据

python - 从列表中创建 pyspark 数据框列,其中列表的长度与数据框的行数相同