Pandas连接上一个当前和下一个tex

2024-09-28 17:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

给定输入数据帧

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

enter image description here

描述

对于给定的事件ID,如示例中所示,我们有1&2个事件。 每个事件都有一个报告时间13\U 01。13是小时,01是分钟。 对于每个报告,有两个数值ReportValX、ReportValY和一个报告文本,例如“Man Arrived near the car”。 对于给定的事件id,在给定的时间(如13\u 02),可能有多个报告。 例如:事件ID 1,时间13\u 02和事件ID 2时间13\u 03。你知道吗

挑战 对于事件ID中的每一个小时,收集上一个文本、当前文本、其他具有相同时间的文本(用标记分隔),以及下一个小时的文本(用文本分隔)

例如:

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. 事件id,reportTime,ReportValX,ReportValY,按原样。

  2. 报告文本\u之前:当时间在13 \u 4。。13_1+的所有文本<; 下一个>;+13_++。。<;13\u 4>;

  3. 报告文本\u报告文本\u当前: 13时4分的课文
  4. 报告文本\u同时报告报告文本:所有 同时发生的文本,用标签隔开。你知道吗
  5. 稍后报告文本:所有文本13_05++13_06+。。。。。13英寸

enter image description here

输入和输出也作为图像提供。你知道吗


Tags: the文本id报告时间事件carwas
1条回答
网友
1楼 · 发布于 2024-09-28 17:04:57

你需要使用groupbyapply来实现你想要的。你知道吗

首先,创建两个新列'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'选择较早、相同或较晚的分钟数。你知道吗

相关问题 更多 >