2016-01-20 26 views
0

我很可能在理解熊猫分组时遇到了麻烦,并且能够生成按类别叠加的直方图。熊猫根据日期分类的直方图,并按类别排序

下面是我正在尝试做的一个工作示例。真的,我正在循环遍历许多文件,每个文件都创建一本字典,然后将其附加到包含所有字典的列表中。然后我把它变成一个数据框并将日期字符串转换为日期时间对象。

import pandas as pd 

# Stand in for dictionaries created by looping over some files 
d1={'fruit':'banana','vege':'spinach','date':'August 1, 2014'} 
d2={'fruit':'banana','vege':'carrots','date':'August 1, 2014'} 
d3={'fruit':'banana','vege':'peas','date':'August 1, 2015'} 
d4={'fruit':'orange','vege':'spinach','date':'August 1, 2014'} 
d5={'fruit':'orange','vege':'carrots','date':'August 1, 2015'} 
data=[d1,d2,d3,d4,d5] 

# Create the dataframe, turn the date strings into datetime objects 
df=pd.DataFrame(data) 
df.date2=pd.to_datetime(df.date) 

# This attempt at plotting gets me a histogram by year, but not divided how it should be. 
df.groupby(df.date2.dt.year).count().plot(kind="bar") 

产生的情节是这样的:

Histogram by year, but unsure why 3 bars for each with category labels

我真正喜欢的是这样的:

Histogram by year, stacked by the text within the category of "fruit"

我已经试过各种其他的东西,如

fr=df.groupby('fruit') 

但随后fr.plot失败,因为

TypeError: Empty 'DataFrame': no numeric data to plot 

预先感谢您的帮助!

回答

2

如何:

df.groupby(df.date2.dt.year)['fruit']\ 
    .value_counts()\ 
    .unstack(1)\ 
    .plot(kind='bar', stacked=True) 

其中产量: enter image description here

0

我会建议使用dateDateTimeIndex。对于pandas 0.17

df['date'] = pd.to_datetime(df.date).dt.year 
df.set_index('date', inplace=True) 
df.groupby(level='date').fruit.value_counts().unstack('fruit').plot.bar(stacked=True) 

enter image description here

+0

不确定的,如果它是大熊猫或Python版本的差异,但你的最后一行并没有为我工作。但是,如果我这样做,它会工作:df.groupby(level ='date')。fruit.value_counts()。unstack()。plot(kind ='bar',stacked = True)。如果我将“水果”包含在叠加偏差中,我会遇到一个错误,如果我使用plot.bar,也会出现错误。使用熊猫版本0.16.1。 – user5817303

+0

需要熊猫= 0.17 – Stefan