2016-12-01 85 views
1

我在用下面的代碼的麻煩:Python Pandas Bokeh Indexerror:列表索引超出範圍 - 爲什麼?

from bokeh.plotting import figure, output_file, show, save 
from bokeh.models import ColumnDataSource 
from bokeh.models import Range1d, LinearAxis 
import pandas as pd 
from pandas import HDFStore 
from bokeh.palettes import Spectral9 

store = pd.HDFStore('<hdf store location>') 
df = pd.DataFrame(store['d1']) 
df = df.rename_axis('Time') 
df.fillna(0) 

#the number of colums is the number of lines that we will make 
numlines = len(df.columns) 

#import colour pallet 
mypalette = Spectral9[0:numlines] 

# remove unwanted columns 
col_list = ['Col1', 'Col2', 'Col3'] 
df = df[col_list] 

# make the figure, 
p = figure(x_axis_type="datetime", title="<title>", width = 800, height = 450) 
p.xaxis.axis_label = 'Date' 
p.yaxis.axis_label = '<y axis label>' 

p.line(df.index, df['Col1'], legend = 'Col1', color = mypalette[0]) 
p.line(df.index, df['Col2'], legend = 'Col2', color = mypalette[1]) 

# add extra y axis 
p.extra_y_ranges = {'Col3': Range1d(start=0, end=1)} 
p.circle(df.index, df['Col3'], legend = 'Col3', color = mypalette[8], 
    y_range_name='Col3') 
p.add_layout(LinearAxis(y_range_name='Col3'), 'right') 


# creates an output file 
output_file('<output file location>') 

#save the plot 
save(p) 

這是我的數據框的樣子:

Time    Col1  Col2  Col3  Col4 
29/11/2016 00:00 4  41  41  55 
29/11/2016 01:00 55  15  61  81 
29/11/2016 02:00 51  75  2   4 
29/11/2016 03:00 21  21  51  9 
etc. 

當我試圖運行上面的代碼,我得到以下錯誤:

IndexError        Traceback (most recent call last) 
<ipython-input-20-9d2c8911130d> in <module>() 
38 
39 # add extra y axis 
---> 40 p.circle(df.index, df['Col3'], legend = 'Col3', color = mypalette[8], y_range_name='Col3') 
41 p.add_layout(LinearAxis(y_range_name='Col3'), 'right') 
42 

IndexError: list index out of range 

我似乎無法弄清楚我做錯了什麼。誰能幫忙?

回答

2

以下各行出現在代碼的頂部。

#the number of colums is the number of lines that we will make 
numlines = len(df.columns) 

#import colour pallet 
mypalette = Spectral9[0:numlines] 

在第一行中,您將numlines設置爲等於您擁有的列數。數據框中只有4列。在第二行中,將mypalette設置爲等於Spectral9的前N個元素,其中n是您擁有的行數。因此,您的調色板僅限於Spectral9的前4個元素。

後來在你的代碼中,你試着抓住mypalette的第9個元素(這與python中的零索引是一樣的)。

p.circle(df.index, df['Col3'], legend = 'Col3', color = mypalette[8], 
    y_range_name='Col3') 

您有限mypalette僅具有4個元素,因此mypalette [8]是超出範圍。如果您想使用該特定顏色,則可以考慮使用color = Spectral9[8]而不是color = mypalette[8]

+0

完美。謝謝。 – pottolom

相關問題