I have two tables. A data table and a filter table. I want to apply the filter table on the data table to select only certain records. When the filter table has a # in a column, the filter is ignored. Additionally, multiple selections can be applied using a | separator.
I have achieved this using a for loop with a bunch of & and | conditions. However, given that my filter table is quite large, I was wondering if there is a more efficient way to achieve this. My filter table looks like:
import pandas as pd
import numpy as np
f = {'business':['FX','FX','IR','IR','CR'],
'A/L':['A','L','A','L','#'],
'Company':['207|401','#','#','207','#']}
filter = pd.DataFrame(data=f)
filter
and the data table looks like:
d = {'business': ['FX','a','CR'],
'A/L': ['A','A','L'],
'Company': ['207','1','2']}
data = pd.DataFrame(data=d)
data
finally the filter looks like:
for counter in range (0, len(filter)):
businessV = str(filter.iat[counter,0])
ALV = str(filter.iat[counter,1])
CompanyV = str(filter.iat[counter,2])
businessV1 = businessV.split("|", 100)
ALV1 = ALV.split("|", 100)
CompanyV1 = CompanyV.split("|", 100)
businessV2 = ('#' in businessV1)| (data['business'].isin(businessV1))
ALV2 = ('#' in ALV1)|(data['A/L'].isin(ALV1))
CompanyV2 = ('#' in CompanyV1)| (data['Company'].isin(CompanyV1))
final_filter = businessV2 & ALV2 & CompanyV2
print(final_filter)
I am trying to find a more efficient way to select the first and last rows in the data table using the filters in the filter table.
Specifically, I am wondering how to :
- Handle cases when the filter table has quite a few more columns
- The current code goes through each row in the data table once for each row in the filter table. For large data sets, this takes way too much time and does not seem very efficient to me.