Skip to content
Advertisement

Dataframe how to update a column based many str values

I am creating a small financial management program which imports my transactions from CSV into Python. I want to assign values to a new column ‘category’ based on strings found in the ‘details’ column. I can do it for one, but my question is how do I do it if I had a huge list of possible strings? For example str.contains('RALPHS') will replace that column value with ‘groceries’, and so on.

For example, below I have a list of strings:

dining = ['CARLS', 'SUBWAY', 'DOMINOS']

and if either of those strings is found in my series, then it will update the respective category series to be ‘dining’.

Here is a small run-able example below.

JavaScript

Thanks much.

Advertisement

Answer

If you have one value, we can use str.extract:

JavaScript
JavaScript

If you have multiple strings to match, we have to delimit your strings first by |, which is the or operator in regular expressions.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement