[英]how to groupby or aggregate Pandas dataframe without an operation
[英]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.