2017-06-01 249 views
2

我有熊貓數據幀網址像pivot_table與組和沒有價值的領域

location dom_category 
3   'edu' 
3   'gov' 
3   'edu' 
4   'org' 
4   'others' 
4   'org' 

,我想這個數據幀像

location edu gov org others 
3   2  1  0  0 
4   0  0  2  1 

的EDU,GOV,組織和其他含有計算具體位置。 我有正確的代碼,但我知道它不是最優化的

url['val']=1 
url_final=url.pivot_table(index=['location'],values='val',columns= 
['dom_category'],aggfunc=np.sum) 

回答

4

首先,如果必要,除去'通過str.strip

然後用groupby與聚集sizeunstack重塑:

df['dom_category'] = df['dom_category'].str.strip("\'") 
df = df.groupby(['location','dom_category']).size().unstack(fill_value=0) 
print (df) 
dom_category edu gov org others 
location       
3    2 1 0  0 
4    0 0 2  1 

或者使用pivot_table

df['dom_category'] = df['dom_category'].str.strip("\'") 
df=df.pivot_table(index='location',columns='dom_category',aggfunc='size', fill_value=0) 
print (df) 
dom_category edu gov org others 
location       
3    2 1 0  0 
4    0 0 2  1 

最後可能轉換索引列和刪除列命名dom_category通過reset_index + rename_axis

df = df.reset_index().rename_axis(None, axis=1) 
print (df) 
    location edu gov org others 
0   3 2 1 0  0 
1   4 0 0 2  1 
2

讓我們用str.stripget_dummiesgroupby

df['dom_category'] = df.dom_category.str.strip("\'") 
df.assign(**df.dom_category.str.get_dummies()).groupby('location').sum().reset_index() 

輸出:

location edu gov org others 
0   3 2 1 0  0 
1   4 0 0 2  1 
+0

'pd.get_dummies(df.dom_category).groupby(df.location)的.sum()。reset_index()' – piRSquared

+0

@piRSquared感謝。 –

3

使用groupbyvalue_counts

看家
擺脫'

df.dom_category = df.dom_category.str.strip("'") 

休息解

df.groupby('location').dom_category.value_counts().unstack(fill_value=0) 

dom_category edu gov org others 
location       
3    2 1 0  0 
4    0 0 2  1 

爲了得到格式化恰到好處

df.groupby('location').dom_category.value_counts().unstack(fill_value=0) \ 
    .reset_index().rename_axis(None, 1) 

    location edu gov org others 
0   3 2 1 0  0 
1   4 0 0 2  1