I've got a routine to read in a CSV file and spit out selected columns that match specific criteria:
CSV Input File looks like this
Name
Role
Login
Phil
Role A | Role B
2024/01/01
Bob
Role A | Role B
2024/02/01
Arthur
Role A | Role C
2024/01/04
Jane
Role B | Role C
2024/01/31
Mary
Role A | Role D
2024/02/12
Liz
Role B | Role F
2024/02/21
Phoebe
Role C | Role D
2023/11/21
Mike
Role E
2024/02/15
Rick
Role D | Role E
2024/01/13
Hilary
Role F
2024/01/11
I have a block of code that matches based on a passed value:
Код: Выделить всё
# Define function to check if a value matches any of the filter values
def matches_filter(value):
value_lower = value.lower()
for filter_value in value_lower.split("|"):
filter_value_lower = filter_value.lower()
for fvals in fltr_values:
if fvals.lower() in filter_value_lower:
return fvals.lower()
return None
# Apply filter
# filtered_df = df[df[fltr_field].apply(matches_filter)]
df[fltr_field + "_matched"] = df[fltr_field].apply(matches_filter)
Name
Role
Login
Phil
Role B
2024/01/01
Bob
Role B
2024/01/01
Jane
Role B
2024/02/03
Mary
Role D
2024/02/02
Liz
Role B
2024/02/12
Phoebe
Role D
2024/02/21
Rick
Role D
2024/01/31
So far, the code will filter so I only get strings containing "Role B" or "Role D" but I'd like to replace the string found with the match criterion, rather than the list of roles. Can someone explain what I need to change here?
To further explain based on comments received so far:
- What is the content of ?
Код: Выделить всё
fltr_field
Код: Выделить всё
fltr_fieldКод: Выделить всё
"Role"- Can you clearly explain what you're trying to do here?
- What is the nature of the column?
Код: Выделить всё
"Login"
Код: Выделить всё
"Login"Источник: https://stackoverflow.com/questions/781 ... new-column