首页 > 解决方案 > 如何在 Pandas Python 中过滤和取消过滤?

问题描述

我有一个要解析的 csv。其中一个步骤需要根据另一行的值更改特定行的值。

我知道的唯一方法(我是 python 的新手)是做熊猫过滤器,效果很好。

我似乎无法找到答案的问题是,我该如何取消过滤它以便我可以做另一个过滤器?

这是我现在的工作代码

我试过爬熊猫参考指南,但我似乎找不到答案。

import pandas as pd
from prompt_toolkit import prompt

filename = input("Enter the path of excel file = ")
abc = pd.read_csv(filename, header=1, dtype=str)

abc = abc[(abc['column_title_A'].str.startswith("300")) | (abc['column_title_A'].str.startswith("860"))]

# change value based on another value in another
abc.loc[abc['column_title_B'] == '29JUL2019', 'column_title_C'] = '15/02/2019'
abc.loc[abc['column_title_B'] == '25FEB2019', 'column_title_C'] = '19/05/2019'

# from here on, how do I unfilter the above to apply another filter below?
abc = abc[(abc['column_title_B'].str.startswith("300")) | (abc['column_title_B'].str.startswith("860"))]

我想要过滤 A 组,然后 unfilter 做另一个过滤器

标签: pythonpandas

解决方案


您可以使用掩码,而不是替换 abc:

mask = (abc['column_title_A'].str.startswith("300")) | (abc['column_title_A'].str.startswith("860"))

# change value based on another value in another
abc.loc[mask & (abc['column_title_B'] == '29JUL2019'), 'column_title_C'] = '15/02/2019'
abc.loc[mask & (abc['column_title_B'] == '25FEB2019'), 'column_title_C'] = '19/05/2019'

mask = abc[(abc['column_title_B'].str.startswith("300")) | (abc['column_title_B'].str.startswith("860"))]
...

推荐阅读