Skip to content
Advertisement

pandas replace values in reference to a user input

I am stuck a little bit, hope you can help me,

I want to replace a value in a pandas df according to a input

Pandas df contains 3 string columns and the default value for category is always 1

Area Name Category
Sales Tom 1
Finance Laura 1
Finance An 1
Ops Roger 1

I have a dict= {‘finance’:’2′ ,’sales’:’3′ ,’ops’:’4′}

And if user inputs for example

selection=’Finance’

The df should look for all the rows that have ‘finance’ in the column Area and replace the default Category of 1 for its corresponding value in the dict (in this case 2)

Area Name Category
Sales Tom 1
Finance Laura 2
Finance An 2
Ops Roger 1

Also, if user inputs a list: selection=[‘Finance’,’Sales’], it should change both:

Area Name Category
Sales Tom 3
Finance Laura 2
Finance An 2
Ops Roger 1

how could I do this?, i tried with combination of iloc and replace but no idea…

Advertisement

Answer

Use numpy’s where as follows:

JavaScript

For example, if the user types in “ops Finance”, the output is

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