My approach is to define an external function to select the relevant PID:
import pandas as pd
df = pd.DataFrame({'Main_FG': ['AB', 'AC', 'AM', 'AP', 'AE', 'RE', 'Rw', 'NA'],
'FG': ['CD,AB,QF', 'AC', 'AM', 'AD, GH, AP', 'GH, ae, ME', 'RE', 'RW', 'RW'],
'PID': ['A.900,B1.56,C1.650', 'R1', 'Q1.45', 'S1.76,S2.56,S3', 'J1.33,J2.39,S3', 'B1.09, B2.56, E2', 'S3.07', 'S3.07'] })
print(df)
Main_FG FG PID
0 AB CD,AB,QF A.900,B1.56,C1.650
1 AC AC R1
2 AM AM Q1.45
3 AP AD, GH, AP S1.76,S2.56,S3 #note the whitespaces between commas
4 AE GH, ae, ME J1.33,J2.39,S3 #note the lowercase
5 RE RE B1.09, B2.56, E2 #note the whitespaces between commas
6 Rw RW S3.07 #note the lowercase
7 NA RW S3.07 #not found
The function also takes care of 3 data cleaning scenarios:
(1) to be case insensitive by matching based on lowercase,
(2) to remove whitespaces when splitting on comma,
(3) to return None when match is not found (thanks @CyrillePontvieux!)
def select_pid(row):
try:
idx = [e.strip().lower() for e in row['FG'].split(',')].index(row['Main_FG'].lower())
return [e.strip() for e in row['PID'].split(',')][idx]
except:
return None
df['SELECTED_PID'] = df.apply(lambda row: select_pid(row), axis=1)
print(df)
Main_FG FG PID SELECTED_PID
0 AB CD,AB,QF A.900,B1.56,C1.650 B1.56
1 AC AC R1 R1
2 AM AM Q1.45 Q1.45
3 AP AD, GH, AP S1.76,S2.56,S3 S3
4 AE GH, ae, ME J1.33,J2.39,S3 J2.39
5 RE RE B1.09, B2.56, E2 B1.09
6 Rw RW S3.07 S3.07
7 NA RW S3.07 None