簡體   English   中英

對熊貓數據框的分組和聚合操作

[英]Groupby and aggregate operation on 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    

我想將DF分組為一些不同的格式:

     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天的嘗試,我不知道如何處理此方法。

任何幫助將不勝感激。

首先,我將創建要聚合的以零和一填充的列,然后使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM