Matplotlib/numpy/pandas IndexError: index 0 is out of bounds for axis 0 with size 0

Matplotlib/numpy/pandas IndexError: index 0 is out of bounds for axis 0 with size 0

我对 numpy 和 pandas 还很陌生,一直遇到以下错误,我不知道如何解决。即使数组形状为 (2603, 1),我仍收到此错误。

IndexError: index 0 is out of bounds for axis 0 with size 0

这导致我在缩放数据和绘制数据时遇到很多问题。我的数据来自:http://bitcoincharts.com/charts/chart.json?m=bitstampUSD#rg360zig12-hourztgSzm1g10zm2g25zv 包含比特币历史。

这是我的代码:

url = 'http://bitcoincharts.com/charts/chart.json?m=bitstampUSD#rg360zig12-hourztgSzm1g10zm2g25zv'
data = json.loads(requests.get(url).content)

df=pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume_btc', 'volume_curr', 'weighted_price'])
df.set_index('timestamp', inplace=True)
df.sort_index(inplace=True)

cols=df.columns
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

close = df['close'].values.reshape(-1, 1)
print(close.shape)

plt.plot(close)

添加

我通过用数字填充 NaN 值解决了这个错误(我取前 5 行的平均值)。

所以问题出在这一行

df.set_index('timestamp', inplace=True)

您将数据帧的索引设置为非 0 的时间戳。Matplotlib 搜索显示错误的索引 0。

您可以重新将其从 0 重新索引到 n-1,然后您将获得所需的输出。