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
x
19
19
1
import numpy as np
2
import pandas as pd
3
4
# reproducible example
5
df = pd.DataFrame()
6
df['Area'] = ['Sales','Finance','Finance','Ops']
7
df['Name'] = ['Tom','Laura','An','Roger']
8
df['Category'] = [1,1,1,1]
9
d = {'finance':2 ,'sales':3 ,'ops':4}
10
11
selection = input("Please type in what areas you are searching for:")
12
# assumes the user is typing in multiple areas split by space
13
selection = selection.lower().split(" ")
14
# loop through each selection and change the category
15
for s in selection:
16
# takes care of searches that aren't in the dictionary
17
if s in d.keys():
18
df['Category'] = np.where(df['Area'].str.lower()==s,d[s],df['Category'])
19
For example, if the user types in “ops Finance”, the output is
JavaScript
1
6
1
Area Name Category
2
0 Sales Tom 1
3
1 Finance Laura 2
4
2 Finance An 2
5
3 Ops Roger 4
6