I'm trying to filter a python data frame based on a sub string in one of the columns.
If the number at position 13&14 of the ID field is <=9, I want to keep the row, if it's > 9, I want to drop the row.
Example:
ABCD-3Z-A93Z-01A-11R-A37O-07 -> keep
ABCD-3Z-A93Z-11A-11R-A37O-07 -> drop
I've managed to get to the below solution, but I think there must be a quicker, more efficient way.
import pandas as pd
# Enter some data. We want to filter out all rows where the number at pos 13,14 > 9
df = {'ID': ['ABCD-3Z-A93Z-01A-11R-A37O-07', 'ABCD-6D-AA2E-11A-11R-A37O-07', 'ABCD-6D-AA2E-01A-11R-A37O-07',
'ABCD-A3-3307-01A-01R-0864-07', 'ABCD-6D-AA2E-01A-11R-A37O-07', 'ABCD-6D-AA2E-10A-11R-A37O-07',
'ABCD-6D-AA2E-09A-11R-A37O-07'],
'year': [2012, 2012, 2013, 2014, 2014, 2017, 2015]
}
# convert to df
df = pd.DataFrame(df)
# define a function that checks if position 13&15 are > 9.
def filter(x):
# that, if x is a string,
if type(x) is str:
if int(float(x[13:15])) <= 9:
return True
else:
return False
else:
return False
# apply function
df['KeepRow'] = df['ID'].apply(filter)
print(df)
# Now filter out rows where "KeepRow" = False
df = df.loc[df['KeepRow'] == True]
print(df)
# drop the column "KeepRow" as we don't need it anymore
df = df.drop('KeepRow', axis=1)
print(df)