python - 如何在 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 做另一个过滤器
解决方案
您可以使用掩码,而不是替换 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"))]
...
推荐阅读
- java - 对表格视图进行排序时出错
- r - 在 r Package LEA 的结构图中按 Q 分数对个体进行分组
- angular - 从 URL 路径读取变量
- java - 如果布尔值是基于某种逻辑生成的,它可以自动更新吗?
- javascript - 如何将指定的选项卡导航到新的 url
- java - 如何使用 StampedLock 乐观锁定?(我无法理解 java doc 中的代码示例)
- react-native - React-navigation:如何在标签导航中设置大中间按钮的样式?
- javascript - Add data to firestore with User ID
- php - 如何使用 Javascript Ajax 销毁 PHP 会话
- javascript - 如何使用 addEventListener 正确添加事件?