首页 > 解决方案 > 如何将多个列统一(折叠)为一个分配唯一值

问题描述

编辑了我之前的问题:

想要区分连接到特定建筑物的特定电梯(以高度表示)的每个设备(四种类型)。

  1. 由于设备没有唯一的 ID,因此要识别它们并通过分组('BldID'、'BldHt'、'Deivce')为每个设备分配唯一 ID,以识别任何特定的“设备”。

  2. 计算他们的测试结果,即在包括几个月的整个持续时间内,在任何特定日期的测试总数 (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

任何提示将不胜感激。

标签: pythonpandas

解决方案


利用:

#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

推荐阅读