Search code examples
python-3.xbokeh

How can I extract the column names from ColumnDataSource in Bokeh 2.4.3?


I'm creating plots using functions and I would like to use the columns names, from the DF, and use them as titles in the chart.

If I have the following:

from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import pandas as pd
import numpy as np      
        
df = pd.DataFrame(np.random.randint(0,100,size=(10, 2)), columns=('Cats', 'Dogs'))

source = ColumnDataSource(df)

How can I then get the column names, I was thinking using source.data but can't figure out exactly how..


Solution

  • If you print the source, you will see it is an object with data in it.

    The data is a dictionary and the keys are the column names and 'index' for the index of the DataFrame.

    print(source.data)
    >>> {
      'index': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
      'Cats': array([87, 56, 98, 10, 30, 89, 40, 51, 17, 13]),
      'Dogs': array([ 9, 11, 73, 76, 67, 46, 64, 62, 93, 71])
    }
    

    and

    print(source.data.keys())
    >>> dict_keys(['index', 'Cats', 'Dogs'])