Strange behabiour with pivot_table

Hi,
here a small piece of code to reproduce my problem

from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.io import show
import pandas as pd
data =pd.DataFrame(data={
‘x_values’:[10.2, 10.48, 10.77, 11.07, 11.38, 11.69, 12.02, 12.35, 12.69, 12.97, 13.26, 13.44, 13.55, 13.4, 13.08, 12.73],
‘y_values’: [3.09, 3.06, 3.02, 2.99, 2.92, 2.85, 2.75, 2.59, 2.44, 2.28, 2.12, 1.93, 1.72, 1.54, 1.47, 1.46],
‘experiment’:[‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’]
})
source = ColumnDataSource(data=data)
p = figure()
p.line(x=‘x_values’, y=‘y_values’, source=source)
show(p)

gives this

and now if I use pivot_table:

data =pd.DataFrame(data={
‘x_values’:[10.2, 10.48, 10.77, 11.07, 11.38, 11.69, 12.02, 12.35, 12.69, 12.97, 13.26, 13.44, 13.55, 13.4, 13.08, 12.73],
‘y_values’: [3.09, 3.06, 3.02, 2.99, 2.92, 2.85, 2.75, 2.59, 2.44, 2.28, 2.12, 1.93, 1.72, 1.54, 1.47, 1.46],
‘experiment’:[‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’, ‘e’]
})
data = pd.pivot_table(data, index=‘x_values’, columns=‘experiment’, values=‘y_values’)
source = ColumnDataSource(data=data)
p = figure()
p.line(x=‘x_values’, y=‘e’, source=source)
show(p)

gives


It seems that pivot_table don’t keep the initial order of my :panda_face:
How can I fixe this ? :thinking:

By advance thank you
Olivier
PS:In my real code I use js_on_change and so a pivot_table is needed …

@odadoun Bokeh just plots the data as you provide it. This seems more like a pandas question, more suited for a pandas help forum.

1 Like

Yeah, not bokeh-related but I think I have the answer for you anyway. Pandas.pivot_table is sorting the index, which in your case is your x values. Looks like sort=True is default according to pandas.pivot_table — pandas 1.4.2 documentation → so try sort=False on the pivot_table.

1 Like

@gmerritt123 thanks but this solution is working with :panda_face: 1.3.0 and I have ‘1.2.5’ :smiling_face_with_tear:

@gmerritt123 I decided to upgrade my :panda_face: and the solution with sort=False work perfectly tahnks

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.