python - 如何将多个列统一(折叠)为一个分配唯一值
问题描述
编辑了我之前的问题:
想要区分连接到特定建筑物的特定电梯(以高度表示)的每个设备(四种类型)。
由于设备没有唯一的 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
如果我 groupby ['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
推荐阅读
- asp.net-mvc - 每次浏览器关闭时如何不让用户重新登录?
- php - 循环限制到 PHP 中 Telegram 的“inline_keyboard”
- excel - 将 Excel 数据导出/写入 CSV 文件时如何保持 Excel 格式?
- webrtc - WebRTC 错误 - 会话错误描述:数据通道类型不匹配。预期 RTP,得到 SCTP
- algorithm - 查找嵌套循环的时间复杂度
- validation - 当用户想要覆盖时,JSF 表单验证跳过特定验证器以进行第二次提交
- python - 如何使用python验证从网上下载的文件的真实性
- ruby - 遍历数组并在 Ruby 中的一行中初始化多个变量
- java - Java Discord API 加入事件
- jquery - 从 JQuery 错误中获取 responseText 错误值?