2013-08-02 68 views
2

我有一個熊貓表DF元素:請在大熊貓行

  course 
ID 
1  physics101 
1  astronomy  
2   maths 
2   another 

我想獲得具有下列結果的表:

  physics101 astronomy  maths another 
ID 
1    True   True False  False 
2    False  False  True   True 

什麼樣的操作呢?

(DF元素被定義的一組類)

回答

1

不知道這是否是最好的方法,嘗試pivot_table

In [65]: pd.pivot_table(df.reset_index(), rows='ID', \ 
         cols='course', aggfunc=lambda x:True, fill_value=False) 
Out[65]: 
course another astronomy maths physics101 
ID           
1  False  True False  True 
2   True  False True  False 
+0

這與廣告一樣。 –

+0

如果你在括號內,你不需要用\ :)打破這一行 –

3

您可以使用crosstab()

import pandas as pd 
from StringIO import StringIO 
data = StringIO("""ID  course 
1  physics101 
1  astronomy  
2   maths 
2   another""") 
df = pd.read_csv(data, delim_whitespace=True) 
pd.crosstab(df.ID, df.course) > 0 

輸出:

course another astronomy maths physics101 
ID           
1  False  True False  True 
2   True  False True  False