如何在Python中过滤和取消过滤?

如何在Python中过滤和取消过滤?,python,pandas,Python,Pandas,我有一个要解析的csv。 其中一个步骤要求根据另一行的值更改特定行的值 我知道的唯一方法(我是python新手)是做熊猫过滤器,它工作得很好 我似乎找不到答案的问题是,我该如何取消过滤,以便可以进行另一次过滤 这是我目前的工作代码 我试过《爬行熊猫参考指南》,但似乎找不到答案 import pandas as pd from prompt_toolkit import prompt filename = input("Enter the path of excel file = ") abc

我有一个要解析的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的集合,然后取消筛选,以执行另一个筛选,而不是替换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"))]
...
您不应该首先进行筛选和覆盖,而应该选择“取消筛选”

我建议这样做:

# filter Admsn_ctr_crs_cd to only show 300XXXX for UG or PG 860XXXX
selector = 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') & selector, 'column_title_C'] = '15/02/2019'
abc.loc[(abc['column_title_B'] == '25FEB2019') & selector, 'column_title_C'] = '19/05/2019'

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

+非常感谢,通过你们提供的修改,我能够实现我想要的。感谢您的回复!