python - 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 代码中工作。
解决方案
用于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")
推荐阅读
- angular - Angular-cli(7.3.8),生产环境,如何将编译好的runtime.js直接写成HTML而不是js引用?
- android - SharedPreferences 仅保存最后一个值
- java - 字符串 B 字赋值
- rest - Azure KeyVault Get Secret API 响应 404 或 401 错误
- ios - Xamarin iOS ITMS-90022 '缺少所需的图标文件'
- javascript - 如何创建一个输出“x”个类的各种实例的函数?
- atom-editor - 如何使用 atom 准确搜索项目中的文件?
- javascript - 如何访问保存在我的快递服务器上的文件?
- firebase - 像 DataModel 这样非常大的类有什么缺点吗?
- angularjs - Angular:每个组件一个模块:反模式?