Janko
Janko

Reputation: 147

dataframe: change value in column when value in another column is in dict

First of how my dataframe looks:

temp = df{'assigned to':('user1','user2','user3'),'model':('ipad air 2','galaxy a5', 'ipad air'), 'type':''}

'assigned to' 'model'    'type'
user1         ipad air 2
user2         galaxy a5
user3         ipad air

the above input is a snippet of the given data, i only added the column type. I also use a dictionary which is:

dictMobile{'galaxy a5':'samsung galaxy a5','galaxy a6':'samsung galaxy a7'}

With this dictionary i replace the values in temp['model'] so the naming is in line. Now i also want to add in the column type 'mobile' if the model shows up in dictMobile or 'tablet' if it doesn't show up.

The best i came up with so far is

if temp['model'] in dictMobile:
    temp['Type'] = 'mobile'
else:
    temp['Type'] = 'tablet'

But this casts me the error 'TypeError: 'Series' objects are mutable, thus they cannot be hashed'.

The result i'm after is:

'assigned to' 'model'    'type'
user1         ipad air 2 tablet
user2         galaxy a5  mobile
user3         ipad air   tablet

Upvotes: 1

Views: 58

Answers (1)

jezrael
jezrael

Reputation: 863531

Use numpy.where with condition with isin for check keys of dict:

df['type'] = np.where(df['model'].isin(dictMobile.keys()), 'mobile','tablet')
print (df)
  assigned to       model    type
0       user1  ipad air 2  tablet
1       user2   galaxy a5  mobile
2       user3    ipad air  tablet

Upvotes: 1

Related Questions