Анализ данных с помощью Pandas – как вывести совпадение в виде нового столбцаPython

Программы на Python
Гость
Анализ данных с помощью Pandas – как вывести совпадение в виде нового столбца

Сообщение Гость »


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)
Based on passing the values "Role B" and "Role D" I'd like to replace whatever is in the Role column with the result of the filter. The net resulting table should therefore look something like this:



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:

Код: Выделить всё

fltr_field
contains the name of the column to filter on (in this case, I'm filtering on the column called .
  • Can you clearly explain what you're trying to do here?
I wish to replace the contents of the Role column with the matched value. The column contains the last login date.


Источник: https://stackoverflow.com/questions/781 ... new-column

Вернуться в «Python»