the ValueError: cannot reindex a non-unique index with a method or limit appears for just cryptocurrency

the ValueError: cannot reindex a non-unique index with a method or limit appears for just cryptocurrency

当我收到错误时,请告诉我以下内容有什么问题:

ValueError:无法使用方法或限制重新索引非唯一索引

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import pandas_datareader as web



data= web.get_data_yahoo("BTC-USD",
                        start = "2015-01-01 ",
                        end = "2021-01-01   ")



btc_dailly_return= data['Adj Close'].pct_change()
btc_monthly_returns = data['Adj Close'].resample('M').ffill().pct_change()

当您使用 resample 时,您必须告诉它您希望如何在您选择的时间范围内组合所有条目。在您的示例中,您要合并一个月内的所有值,您可以通过将它们加在一起、取平均值、标准差、最大值等来合并它们。所以您必须告诉 Pandas 什么你想通过提供一个额外的方法来做:

data['col'].resample('M').sum()
data['col'].resample('M').max()
data['col'].resample('M').mean()

在您的情况下,last() 可能是最合理的,因此只需将最后一行更改为:

btc_monthly_returns = data['Adj Close'].resample('M').last().ffill().pct_change()

至于为什么只有 BTC-USD 才会出现错误:那个特定的 table 有一个重复的日期条目,导致 ffill() 抛出错误。 last()(或任何其他缩减类型聚合器)不关心重复项。

通常,resample('<method>').ffill() 应该用于 上采样 数据,即将月份列表变成日期列表。在这种情况下,ffill() 将使用先前有效时间戳的值填充所有新生成的时间戳。您的示例 downsamples,因此应该调用像 lastsummean 这样的缩减聚合器。