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:

import numpy as np
import pandas as pd

# reproducible example
df = pd.DataFrame()
df['Area'] = ['Sales','Finance','Finance','Ops']
df['Name'] = ['Tom','Laura','An','Roger']
df['Category'] = [1,1,1,1]
d = {'finance':2 ,'sales':3 ,'ops':4}

selection = input("Please type in what areas you are searching for:")
# assumes the user is typing in multiple areas split by space
selection = selection.lower().split(" ")
# loop through each selection and change the category
for s in selection:
# takes care of searches that aren't in the dictionary
    if s in d.keys():
        df['Category'] = np.where(df['Area'].str.lower()==s,d[s],df['Category'])

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

    Area    Name    Category
0   Sales   Tom     1
1   Finance Laura   2
2   Finance An      2
3   Ops     Roger   4
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement