سؤال

I have a Pandas dataframe:

     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    

I'd like to groupby the DF into a bit different format:

     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         

I want to get an aggregated report from the original table where the entries are grouped by Date and Type and then split into various types. I have not idea how to handle this approach after 2 days of trying.

Any help would be greatly appreciated.

هل كانت مفيدة؟

المحلول

Firstly I would create the columns you wish to aggregate populated with zeros and ones, and then use groupby and do a simple sum of the values...

I didnt get to try this out, but I think the following should work:

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top