python-3.x - 使用下一行值作为条件
问题描述
假设我有一个日志文件被解析并放入pandas.DataFrame
.
我有兴趣创建一个新boolean
列,该列True
仅在当前行包含EXPRESSION_1
字符串且下一行包含EXPRESSION_2
表达式时才具有。
我可以只用一个表达式来做,如下Example 1
所示:
示例 1:
import pandas as pd
EXPRESSION_1 = 'Starts streaming the stream rtspsrc'
EXPRESSION_2 = 'initializing gst pipeline'
df = pd.DataFrame(
{
'message': [
'Some log text',
'Some log text',
'Starts streaming the stream rtspsrc',
'initializing gst pipeline',
'Some log text',
'Starts streaming the stream rtspsrc',
'initializing gst pipeline',
'Some log text',
]
}
)
df.loc[:, 'process_started'] = df.loc[:, 'message'].apply(lambda msg: True if msg.find(EXPRESSION_1) > -1 else False)
df
示例 1 的输出:
message process_started
0 Some log text False
1 Some log text False
2 Starts streaming the stream rtspsrc True
3 Some log text False
4 Some log text False
5 Starts streaming the stream rtspsrc True
6 initializing gst pipeline False
7 Some log text False
期望的输出:
message process_started
0 Some log text False
1 Some log text False
2 Starts streaming the stream rtspsrc False # <= Note the False here
3 Some log text False
4 Some log text False
5 Starts streaming the stream rtspsrc True
6 initializing gst pipeline False
7 Some log text False
在此先感谢您的任何建议。
解决方案
您可以使用该shift
操作来执行此操作。shift(-1)
代码中的将列message
向上移动 1(简单来说):
import pandas as pd
EXPRESSION_1 = 'Starts streaming the stream rtspsrc'
EXPRESSION_2 = 'initializing gst pipeline'
df = pd.DataFrame(
{
'message': [
'Some log text',
'Some log text',
'Starts streaming the stream rtspsrc',
'Some log text',
'Some log text',
'Starts streaming the stream rtspsrc',
'initializing gst pipeline',
'Some log text',
]
}
)
df.loc[:, 'process_started'] = df.loc[:, 'message'].apply(lambda msg: True if msg.find(EXPRESSION_1) > -1 else False)
df.loc[(df['message'] == EXPRESSION_1) & (df['message'].shift(-1) == EXPRESSION_2), 'process_started'] = True
df.loc[(df['message'] == EXPRESSION_1) & (df['message'].shift(-1) != EXPRESSION_2), 'process_started'] = False
输出:
message process_started
0 Some log text False
1 Some log text False
2 Starts streaming the stream rtspsrc False
3 Some log text False
4 Some log text False
5 Starts streaming the stream rtspsrc True
6 initializing gst pipeline False
7 Some log text False
推荐阅读
- angular - 为我自己的角度包使用其他包
- math - PCA 的主要成分何时构成数据集的基础?
- regex - 如何通过正则表达式分隔的拆分函数将VBA中的字符串拆分为数组
- python - 从 Python 调用时与 openssl 的结果不一致
- ajax - Webix:更新树形菜单数据的 AJAX 响应
- constraints - 基于 System Verilog 中运行时数据的加权随机化
- sql - 如何在 SQL 中对数字进行四舍五入
- vmware-clarity - 为 1.0 版自定义 Clarity 主题
- java - 从网页获取 Java 或 C 程序的输入?
- c++ - Python实现不适用于c ++中的相同逻辑