首页 > 解决方案 > 熊猫连接上一个当前和下一个文本

问题描述

给定输入数据框

Event_id,reportTime,ReportValX,ReportValY,ReportText

1,13_01,13,1,Man Arrived near the car
1,13_02,13,2.2,The Car was fast
1,13_02,13,2.1,The lights were on.
1,13_03,13,3,The man hit the car
2,13_01,13,1,Cat was on the mat
2,13_02,13,2.2,mat was red
2,13_03,13,3.1,Dad is a man
2,13_03,13,3,Dad has a hat

在此处输入图像描述

描述

对于给定的事件 ID,如示例中我们有 1 和 2 个事件。对于每个事件,都有一个报告时间 13_01。13 是小时,01 是分钟。对于每个报告,有两个数值 ReportValX,ReportValY 和一个报告文本,例如“,Man Arrived near the car”。对于给定的事件 ID,在给定时间(例如 13_02)可能有多个报告。例如:事件 ID 1,时间 13_02 和事件 ID 2 时间 13_03。

Challenge For Every Hour in an Event ID,收集前一个Text,当前Text,其他相同时间的Text,用标签分隔,后面的文字用Text分隔

例如:

Event_id,reportTime,ReportValX,ReportValY,ReportText_Before,Reprt Text_Current,Report Text Same Time,Report Text Later

1,13_01,13,1,,Man Arrived near the car,Man Arrived near the car,The Car was fast. <NEXT> The lights were on. <NEXT> The man hit the car
1,13_02,13,2.2,Man Arrived near the car,The Car was fast,The Car was fast <NEXT> The lights were on.,The man hit the car

规则

  1. Event_id,reportTime,ReportValX,ReportValY,按原样。

  2. ReportText_Before:当时间在 13_4 时 .. 13_1 的所有文本 +< Next> + 13_02 + + .. <13_4>

  3. ReportText_Reprt Text_Current:13_4 处的文本
  4. ReportText_Reprt Report Text Same Time:所有同时发生的文本,13_4 以标签分隔。
  5. 稍后报告文本:所有文本 13_05 + + 13_06 + ..... 13_N。

在此处输入图像描述

输入和输出也作为图像提供。

标签: pythonpandas

解决方案


您需要玩一下groupby申请以实现您想要的。

首先,创建两个新列'Hour''Minute'更轻松地识别时间。

df["Hour"], df["Minute"] = zip(*df['reportTime'].apply(lambda x : list(map(int, x.split('_')))))

然后编写一个自定义函数来制作新列并使用groupbyapply使用它。

def makerep(x):
    res = x[['Event_id','reportTime','ReportValX','ReportValY']]
    res['ReportText_Before'] = x.apply(lambda el : '<NEXT>'.join(x['ReportText'].loc[x['Minute'] < el['Minute']]), axis=1)
    res['ReportText_Current'] = x['ReportText']
    res['ReportText_SameTime'] = x.apply(lambda el : '<NEXT>'.join(x['ReportText'].loc[x['Minute'] == el['Minute']]), axis=1)
    res['ReportText_Later'] = x.apply(lambda el : '<NEXT>'.join(x['ReportText'].loc[x['Minute'] > el['Minute']]), axis=1)
    return res

ddf = df.groupby(['Event_id', 'Hour']).apply(makerep)

在连接新列中的字符串时,您可以对'Event_id'和进行分组'Hour',并使用它来选择更早、相同或更晚的分钟。'Minute'


推荐阅读