用散景绘制一个groupby对象

问题描述 投票:0回答:3

考虑以下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') )

(现实生活中的例子有大量不同的群体。)有没有简洁的方法来做到这一点?

pandas pandas-groupby bokeh
3个回答
1
投票

我刚刚发现以下工作

gby = df.groupby('g')
gby.apply( lambda d: p.line( 'x', 'y', source=d ) )

(但它有一些缺点)。

有什么好主意吗?


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)

结果:

enter image description here


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 )
© www.soinside.com 2019 - 2024. All rights reserved.