2013-08-02 136 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