gpt4 book ai didi

python - 如何在 Pandas Python 中过滤和取消过滤?

转载 作者:行者123 更新时间:2023-12-01 08:20:07 25 4
gpt4 key购买 nike

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

我知道的唯一方法(我是Python新手)是做pandas过滤器,它效果很好。

我似乎找不到答案的问题是,如何取消过滤它以便我可以进行另一个过滤?

这是我现在的工作代码

我尝试爬行 pandas 引用指南,但我似乎找不到答案。

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"))]
...

关于python - 如何在 Pandas Python 中过滤和取消过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com