首页 > 解决方案 > pandas + python 列中最后 3 个值中的模式序列

问题描述

我需要帮助来查找列中的序列模式,例如

colour --- match
blue    no match
orange  no match
orange  no match
blue    no match
orange  no match
orange  no match
orange  **match**

在上面的数据框中,我们有 2 列颜色和匹配。我需要在“颜色”列中找到序列,它应该在列中找到最后 3 个值(蓝色、橙色、橙色、橙色(当前单元格)),如果匹配,则需要更新下一列匹配。我正在寻找此代码以在 python 代码中工作。

标签: pythonpandas

解决方案


用于shift该目的:当其中一个等于前两个df["new_col"] = df.col.eq(df.col.shift(1)) & df.col.eq(df.col.shift(2))值时,创建一个布尔值系列!col

输出:

0    False
1    False
2    False
3    False
4    False
5    False
6     True
Name: test, dtype: bool

编辑:如果你想转换回“不匹配”/“匹配”值,你可以简单地添加这个

df["col"] = np.where(df["col"] == False, "mismatched", "matched")


推荐阅读