我有两个DataFrames (trail1和trail2),它们包含以下列: Genre、City和Number Sold。现在,我想为这两个数据集创建一个条形图,以便并排比较流派与总销量。对于每个类型,我想要两个条形图:一个表示轨迹1,另一个表示轨迹2。
我如何使用Pandas来实现这一点?
我尝试了以下方法,但不起作用。
gf1 = df1.groupby(['Genre'])
gf2 = df2.groupby(['Genre'])
gf1Plot = gf1.sum().unstack().plot(kind='bar, stacked=False)
gf2Plot = gf2.sum().unstack().plot(kind='bar, ax=gf1Plot, stacked=False)
我希望能够看到每个流派(例如:辛辣、甜味、酸味等)的trail1数据集与trial2数据集的比较情况。
我也尝试过使用concat,但我不知道如何在同一张图上绘制连接的DataFrame来比较这两个键。
DF = pd.concat([df1,df2],keys=['trail1','trail2'])
发布于 2015-07-07 18:35:49
我找到了我的问题的答案。我欢迎其他人发布更好的方法。
解决方案:
df1 = pd.DataFrame(myData1, columns=['Genre', 'City', 'Sold'])
df2 = pd.DataFrame(myData2, columns=['Genre', 'City', 'Sold'])
df1['Key'] = 'trail1'
df2['Key'] = 'trail2'
DF = pd.concat([df1,df2],keys=['trail1','trail2'])
DFGroup = DF.groupby(['Genre','Key'])
DFGPlot = DFGroup.sum().unstack('Key').plot(kind='bar')
以下是生成的图形的示例:
发布于 2015-07-07 01:57:34
你是对的,但是你想要的是merge
而不是concat
。试试这个:
DF = pd.merge(df1,df2,on=['Genre','City'])
DF.Groupby([['Genre','City']]).sum().unstack().plot(kind = 'bar')
https://stackoverflow.com/questions/31258134
复制相似问题