简体   繁体   English

数据框根据条件合并两个连续的行

[英]Dataframe merge two consecutive rows based on condition

This is my DataFrame这是我的数据框

         id   group  sensor        sdate   stime   status
0   US-2222  BUTTON  LA-1212  2022-06-21  11:00:00     ON
1   US-2222  BUTTON  LA-1212  2202-06-21  11:30:00    OFF
2   US-6666  BUTTON  LA-4545  2022-06-21  06:00:00     ON
3   US-6666  BUTTON  LA-4545  2022-06-21  06:30:00    OFF
4   US-6666  MOTION  LA-4545  2022-06-21  09:00:00     ON
5   US-6666  MOTION  LA-4545  2022-06-21  09:20:00    OFF
6   US-6666  MOTION  LA-4545  2022-06-21  18:00:00     ON

I need to merge consecutive rows for each "Sensor" based on "status".我需要根据“状态”合并每个“传感器”的连续行。 The output should look like this输出应如下所示

         id  group   sensor     sdate        stime  status       stime2     status2
0   US-2222  BUTTON  LA-1212  2022-06-21  11:00:00     ON       11:30:00        OFF
2   US-6666  BUTTON  LA-4545  2022-06-21  06:00:00     ON       06:30:00        OFF
4   US-6666  MOTION  LA-4545  2022-06-21  09:00:00     ON       09:20:00        OFF

Thanks谢谢

You can use a custom pivot :您可以使用自定义pivot

cols = ['id', 'group', 'sensor', 'sdate']
out = (df
 .assign(idx=df.groupby(cols).cumcount().floordiv(2),
         col=lambda d: d.groupby(cols+['idx']).cumcount().astype(str)
        )
 .pivot(index=cols+['idx'], columns='col', values=['stime', 'status'])
 .sort_index(level=1, axis=1) 
 .pipe(lambda d: d.set_axis(d.columns.map('_'.join), axis=1))
 .dropna()
 .reset_index()
)

output:输出:

        id   group   sensor       sdate  idx status_0   stime_0 status_1   stime_1
0  US-2222  BUTTON  LA-1212  2022-06-21    0       ON  11:00:00      OFF  11:30:00
1  US-6666  BUTTON  LA-4545  2022-06-21    0       ON  06:00:00      OFF  06:30:00
2  US-6666  MOTION  LA-4545  2022-06-21    0       ON  09:00:00      OFF  09:20:00

Thanks !谢谢 ! I found a crude but simpler light weight solution.我找到了一个粗略但更简单的轻量级解决方案。

respStr = "["
sList = mClass_sLog_japiapp.objects.all()
t = len(sList)-1
for i in range (0, t, 2):
    R = sList[i]
    respStr += "{"
    s = "\"{}\" : \"{}\",".format("GROUP",R.group)
    respStr += s
    s = "\"{}\" : \"{}\",".format("SENSOR",R.plate)
    respStr += s
    s = "\"{}\" : \"{}\",".format("DATE",R.sdate)
    respStr += s
    s = "\"{}\" : \"{}\",".format("FTIME",R.stime)
    respStr += s
    # s = "\"{}\" : \"{}\",".format("FSTATUS",R.status)
    # respStr += s
    s = "\"{}\" : \"{}\"".format("TOTIME",sList[i+1].stime)
    respStr += s
    # s = "\"{}\" : \"{}\"".format("TSTATUS",sList[i+1].status)
    # respStr += s
    respStr += "},"
respStr += "]"
respStr = respStr.replace("},]", "}]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM