2013-02-21 73 views
11

假设我有这样创造了一个数据帧:打开熊猫据帧串到柱状图

import pandas as pd 
s1 = pd.Series(['a', 'b', 'a', 'c', 'a', 'b']) 
s2 = pd.Series(['a', 'f', 'a', 'd', 'a', 'f', 'f']) 
d = pd.DataFrame({'s1': s1, 's2', s2}) 

有在真实数据串相当多的稀疏。我想创建一个字符串出现的直方图,看起来像d.hist()(例如,用子图)为s1和s2(每个子图一个)生成的内容。

只是做d.hist()给出了这样的错误:

/Library/Python/2.7/site-packages/pandas/tools/plotting.pyc in hist_frame(data, column, by, grid, xlabelsize, xrot, ylabelsize, yrot, ax, sharex, sharey, **kwds) 
    1725   ax.xaxis.set_visible(True) 
    1726   ax.yaxis.set_visible(True) 
-> 1727   ax.hist(data[col].dropna().values, **kwds) 
    1728   ax.set_title(col) 
    1729   ax.grid(grid) 

/Library/Python/2.7/site-packages/matplotlib/axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs) 
    8099    # this will automatically overwrite bins, 
    8100    # so that each histogram uses the same bins 
-> 8101    m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) 
    8102    if mlast is None: 
    8103     mlast = np.zeros(len(bins)-1, m.dtype) 

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/function_base.pyc in histogram(a, bins, range, normed, weights, density) 
    167    else: 
    168     range = (a.min(), a.max()) 
--> 169   mn, mx = [mi+0.0 for mi in range] 
    170   if mn == mx: 
    171    mn -= 0.5 

TypeError: cannot concatenate 'str' and 'float' objects 

我想我可以手动完成对每个系列,做一个value_counts(),然后绘制它的柱状图,并手动创建的次要情节。我想检查是否有更简单的方法。

回答

1

我会将系列推入collections.Counterdocumentation)(您可能需要先将其转换为列表)。我不是pandas专家,但我认为你应该能够将Counter对象折回到由字符串索引的Series中,然后用它来绘制你的图。

这不起作用,因为当它试图猜测bin边缘应该在哪里时会(错误地)引发错误,这对字符串没有意义。

+0

ag,打我吧!是的,计数器是工作的工具! – 2013-02-21 01:06:01

+1

感谢您的回复。 value_counts做同样的事情,是一个系列 - >系列转换(所以不需要强制它回到一个系列)。我想我想知道是否有一些选项可以为这个特定的字符串情况自动计算和绘图,因为有一个用于整数。 – amatsukawa 2013-02-21 01:31:26

6

您可以使用pd.value_counts(value_counts也是一系列方法):

In [20]: d.apply(pd.value_counts) 
Out[20]: 
    s1 s2 
a 3 3 
b 2 NaN 
c 1 NaN 
d NaN 1 
f NaN 3 

,比绘制产生的数据帧。

19

重新创建数据框:

import pandas as pd 
s1 = pd.Series(['a', 'b', 'a', 'c', 'a', 'b']) 
s2 = pd.Series(['a', 'f', 'a', 'd', 'a', 'f', 'f']) 
d = pd.DataFrame({'s1': s1, 's2': s2}) 

为了大选的获得所期望的直方图:

d.apply(pd.value_counts).plot(kind='bar', subplots=True) 

enter image description here

的OP在问题中提到pd.value_counts。我认为缺失的部分只是没有理由“手动”创建所需的条形图。

d.apply(pd.value_counts)的输出是一个熊猫数据框。我们可以像任何其他数据框一样绘制值,并选择subplots=True选项给我们我们想要的。