2014-05-11 144 views
0

合计操作我有一个熊猫数据帧:GROUPBY和熊猫据帧

 Date  Type  Section  Status 
-------------------------------------------- 
0  1-Apr Type1  A   Present 
1  1-Apr Type2  A   Absent 
2  1-Apr Type2  A   Present 
3  1-Apr Type1  B   Absent 
4  2-Apr Type1  A   Present 
5  2-Apr Type2  C   Present 
6  2-Apr Type2  C   Present  

我想的DF GROUPBY到有点不同格式:

 Date  Type  A_Pre A_Abs B_Pre B_Abs C_Pre C_Abs 
------------------------------------------------------------------------------ 
0  1-Apr Type1  1 0  0  1  0  0 
1    Type2  1 1  0  0  0  0 
2  2-Apr Type1  1 0  0  0  0  0   
3    Type2  0 0  0  0  1  1   

我想要得到的聚合从原始表格报告条目按日期和类型分组,然后拆分为各种类型。在尝试2天后,我不知道如何处理这种方法。

任何帮助将不胜感激。

+0

这是这几乎是重复的:http://stackoverflow.com/questions/23580009/data-processing-with-adding-columns-dynamically-in-python-pandas-dataframe – Jeff

+0

感谢您的链接,检查出来。如果我能得到我的答案,我会在这里更新它。非常感谢。 –

+0

其实你的问题可能会更简单,试试:df.groupby(..)['Status']。apply(pd.get_dummies) – Jeff

回答

1

首先,我将创建要聚集填充零和的,然后用GROUPBY并做值的简单总和列...

我没有得到尝试了这一点,但我认为下面应该工作:

Present = ['A_Pre', 'B_Pre', 'C_Pre' ] 
Absent = ['A_Abs', 'B_Abs', 'C_Abs' ] 

for string in Present: 
    DF[string] = pd.Series([1 if stat == 'Present' and sect == string[0] else 0 
          for stat, sect in zip(DF['Status'], DF['Section'])], 
          index = DF.index) 
for string in Absent: 
    DF[string] = pd.Series([1 if stat == 'Absent' and sect == string[0] else 0 
          for stat, sect in zip(DF['Status'], DF['Section'])], 
          index = DF.index) 

DF.groupby(['Date', 'type']).agg(sum)