2013-02-21 76 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選項給我們我們想要的。