我有一个有两列的df --时间戳和文本。我试图用True/false (1/0)标签标记数据。条件是,如果文本中存在"error“一词,则在输入之前3-4小时内的所有条目都应该得到一个标签,而其他条目则为0。例如:像这样的df:
time text
15:00 a-ok
16:01 fine
17:00 kay
18:00 uhum
19:00 doin well
20:00 is error
20:05 still error
21:00 fine again应转化为:
time text error coming
15:00 a-ok 0
16:01 fine 1
17:00 kay 1
18:00 uhum 1
19:00 doin well 1
20:00 is error 0
20:05 still error0
21:00 fine again 0我读到了一些关于用.rolling滑动窗口的东西,但是我很难把它们整合在一起。
发布于 2019-05-17 11:03:14
其思想是将时间转换为timedeltas,过滤带有错误的时间差,并为每个值创建带有logical_or.reduce的掩码,使用反向m1的链掩码以避免error的值,并将True/False转换为1/0映射的整数:
td = pd.to_timedelta(df['time'].astype(str) + ':00')
m1 = df['text'].str.contains('error')
v = td[m1]
print (v)
5 20:00:00
6 20:05:00
Name: time, dtype: timedelta64[ns]
m2 = np.logical_or.reduce([td.between(x - pd.Timedelta(4, unit='h'), x) for x in v])
df['error coming'] = (m2 & ~m1).astype(int)
print (df)
time text error coming
0 15:00 a-ok 0
1 16:01 fine 1
2 17:00 kay 1
3 18:00 uhum 1
4 19:00 doin well 1
5 20:00 is error 0
6 20:05 still error 0
7 21:00 fine again 0编辑:
df['time'] = pd.to_datetime(df['time'])
print (df)
time text
0 2019-01-26 15:00:00 a-ok
1 2019-01-26 16:01:00 fine
2 2019-01-26 17:00:00 kay
3 2019-01-26 18:00:00 uhum
4 2019-01-26 19:00:00 doin well
5 2019-01-26 20:00:00 is error
6 2019-01-26 20:05:00 still error
7 2019-01-26 21:00:00 fine again
print (df.dtypes)
time datetime64[ns]
text object
dtype: objectm1 = df['text'].str.contains('error')
v = df.loc[m1, 'time']
print (v)
5 2019-01-26 20:00:00
6 2019-01-26 20:05:00
Name: time, dtype: datetime64[ns]
m2 = np.logical_or.reduce([df['time'].between(x - pd.Timedelta(4, unit='h'), x) for x in v])
df['error coming'] = (m2 & ~m1).astype(int)
print (df)
time text error coming
0 2019-01-26 15:00:00 a-ok 0
1 2019-01-26 16:01:00 fine 1
2 2019-01-26 17:00:00 kay 1
3 2019-01-26 18:00:00 uhum 1
4 2019-01-26 19:00:00 doin well 1
5 2019-01-26 20:00:00 is error 0
6 2019-01-26 20:05:00 still error 0
7 2019-01-26 21:00:00 fine again 0矢量化溶液:
m1 = df['text'].str.contains('error')
v = df.loc[m1, 'time']
print (v)
5 2019-01-26 20:00:00
6 2019-01-26 20:05:00
Name: time, dtype: datetime64[ns]
a = v - pd.Timedelta(4, unit='h')
m = (a.values < df['time'].values[:, None]) & (v.values > df['time'].values[:, None])
df['error coming'] = (m.any(axis=1) & ~m1).astype(int)
print (df)
time text error coming
0 2019-01-26 15:00:00 a-ok 0
1 2019-01-26 16:01:00 fine 1
2 2019-01-26 17:00:00 kay 1
3 2019-01-26 18:00:00 uhum 1
4 2019-01-26 19:00:00 doin well 1
5 2019-01-26 20:00:00 is error 0
6 2019-01-26 20:05:00 still error 0
7 2019-01-26 21:00:00 fine again 0https://stackoverflow.com/questions/56184859
复制相似问题