[英]How to unify (collapse) multiple columns into one assigning unique values
编辑了我之前的问题:
想要区分连接到特定建筑物的特定电梯(以高度表示)的每个设备(四种类型)。
由于设备没有唯一的 ID,想要识别它们并通过分组('BldID'、'BldHt'、'Deivce')为每个设备分配唯一的 ID,以识别任何特定的“设备”。
计算他们的测试结果,即在由几个月组成的整个持续时间内,任何特定日期的测试总数 (NG + OK) 中失败 (NG) 的次数。
原始数据框看起来像这样
BldgID BldgHt Device Date Time Result
1074 34.0 790 2018/11/20 10:30 OK
1072 31.0 780 2018/11/19 11:10 NG
1072 36.0 780 2018/11/17 05:30 OK
1074 10.0 790 2018/11/19 06:10 OK
1074 10.0 790 2018/12/20 11:50 NG
1076 17.0 760 2018/08/15 09:20 NG
1076 17.0 760 2018/09/20 13:40 OK
由于“时间”无关紧要,因此将其删除。 想要找出每组每天 [NG] 的数量(由“BldgID”、“BlgHt”、“Device”组成)。
#aggregate both functions only once by groupby
df1 = mel_df.groupby(['BldgID','BldgHt','Device','Date'])\
['Result'].agg([('NG', lambda x :(x=='NG').sum()), \
('ALL','count')]).round(2).reset_index()
#create New_ID by insert with Series with zero fill 3 values
s = pd.Series(np.arange(1, len(mel_df2) + 1),
index=mel_df2.index).astype(str).str.zfill(3)
mel_df2.insert(0, 'New_ID', s)
现在过滤后的 DataFrame 看起来像:
print (mel_df2)
New_ID BldgID BldgHt Device Date NG ALL
1 001 1072 31.0 780 2018/11/19 1 2
8 002 1076 17.0 760 2018/11/20 1 1
如果我分组 ['BldgID', 'BldgHt', 'Device', 'Date'] 那么我每天都会得到 'NG'。 但它会以不同的方式考虑每一天,如果我分配“唯一”ID,我可以绘制唯一设备在每隔一天的行为方式。
如果我按 ['BldgId', 'BldgHt', 'Device'] 分组,那么我会得到该集合(或唯一设备)的整体“NG”,这不是我的目标。
What I want to achieve is:
print (mel_df2)
New_ID BldgID BldgHt Device Date NG ALL
001 1072 31.0 780 2018/11/19 1 2
1072 31.0 780 2018/12/30 3 4
002 1076 17.0 760 2018/11/20 1 1
1076 17.0 760 2018/09/20 2 4
003 1072 36.0 780 2018/08/15 1 3
任何提示将不胜感激。
用:
#aggregate both aggregate function only in once groupby
df1 = mel_df.groupby(['BldgID','BldgHt','Device','Date'])\
['Result'].agg([('NG', lambda x :(x=='NG').sum()), ('ALL','count')]).round(2).reset_index()
#filter non 0 rows
mel_df2 = df1[df1.NG != 0]
#filter first rows by Date
mel_df2 = mel_df2.drop_duplicates('Date')
#create New_ID by insert with Series with zero fill 3 values
s = pd.Series(np.arange(1, len(mel_df2) + 1), index=mel_df2.index).astype(str).str.zfill(3)
mel_df2.insert(0, 'New_ID', s)
问题数据的输出:
print (mel_df2)
New_ID BldgID BldgHt Device Date NG ALL
1 001 1072 31.0 780 2018/11/19 1 1
8 002 1076 17.0 780 2018/11/20 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.