请考虑以下MWE。
from pandas import DataFrame
from bokeh.plotting import figure
data = dict(x = [0,1,2,0,1,2],
y = [0,1,2,4,5,6],
g = [1,1,1,2,2,2])
df = DataFrame(data)
p = figure()
p.line( 'x', 'y', source=df[ df.g == 1 ] )
p.line( 'x', 'y', source=df[ df.g == 2 ] )
理想情况下,我想将最后一行压缩成一行:
p.line( 'x', 'y', source=df.groupby('g') )
(现实生活中的示例有大量的可变组。)是否有任何简洁的方法?
答案 0 :(得分:1)
我刚刚发现以下方法有效
gby = df.groupby('g')
gby.apply( lambda d: p.line( 'x', 'y', source=d ) )
(尽管有一些缺点)。
有更好的主意吗?
答案 1 :(得分:1)
我没有提出df.groupby
,所以我使用了df.loc
,但也许multi_line是您追求的目标:
from pandas import DataFrame
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
data = dict(x = [0, 1, 2, 0, 1, 2],
y = [0, 1, 2, 4, 5, 6],
g = [1, 1, 1, 2, 2, 2])
df = DataFrame(data, index = data['g'])
dfs = [DataFrame(df.loc[i].values, columns = df.columns) for i in df['g'].unique()]
source = ColumnDataSource(dict(x = [df['x'].values for df in dfs], y = [df['y'].values for df in dfs]))
p = figure()
p.multi_line('x', 'y', source = source)
show(p)
结果:
答案 2 :(得分:1)
这是Tony的解决方案,略有简化。
import pandas as pd
from bokeh.plotting import figure
data = dict(x = [0, 1, 2, 0, 1, 2],
y = [0, 1, 2, 4, 5, 6],
g = [1, 1, 1, 2, 2, 2])
df = pd.DataFrame(data)
####################### So far as in the OP
gby = df.groupby('g')
p = figure()
x = [list( sdf['x'] ) for i,sdf in gby]
y = [list( sdf['y'] ) for i,sdf in gby]
p.multi_line( x, y )