0

I have a key value pairs. I want to find a key of values exists in a dataframe and assign those key as new column.

For e.g I have a dictionary

 "low" : [1,4] "high" : [2,5] "medium":[3]

c1 
1  
2  
3  
4  
5   

and expecting output like this

c1 c2
1  low
2  high
3  medium
4  low
5  high 
sara
  • 45
  • 2
  • 13

1 Answers1

0

Use Series.map, but first generate dictionary in dict comprehension with split, also convert column c1 to string if filled by integers:

d = {"low" : '1,4', "high" : '2,5', "medium":'3'}

d1 = {x:k for k, v in d.items() for x in v.split(',')}
print (d1)
{'1': 'low', '4': 'low', '2': 'high', '5': 'high', '3': 'medium'}

df['c2'] = df['c1'].astype(str).map(d1)
print (df)
   c1      c2
0   1     low
1   2    high
2   3  medium
3   4     low
4   5    high

Solution if lists in dictionary:

d = {"low" : [1,4], "high" : [2,5], "medium":[3]}

d1 = {x:k for k, v in d.items() for x in v}
print (d1)
{1: 'low', 4: 'low', 2: 'high', 5: 'high', 3: 'medium'}

df['c2'] = df['c1'].map(d1)
print (df)
   c1      c2
0   1     low
1   2    high
2   3  medium
3   4     low
4   5    high
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • i got following error "AttributeError: 'list' object has no attribute 'split' @jezrael – sara Mar 12 '20 at 11:11
  • sorry.. but now all the values got mapped to one key. – sara Mar 12 '20 at 11:22
  • @sara - Maybe main problem is I have to guess format of dictionary, `"low" : 1,4 "high" : 2,5 "medium":3` is not valid, can you add valid dict to quation? – jezrael Mar 12 '20 at 11:23
  • @sara - Thanks, can you show output of my solution in question? For me working nice. – jezrael Mar 12 '20 at 11:40
  • This is the dictionary i have.. dictionary = {} dictionary["low"] = list1 dictionary["high"] = list2 dictionary['medium'] = list3 dictionary['normal'] = list4 and when i applied your function, all the values got mapped to normal... – sara Mar 13 '20 at 09:38
  • @sara - So if use `d = {"low" : list1, "high" : list2, "medium":list3}` instead `d = {"low" : [1,4], "high" : [2,5], "medium":[3]}` working my second solution? – jezrael Mar 13 '20 at 09:40
  • no its not working.. if i use first solution, list object has no attribute 'split.. and for second solution all the values got mapped to normal... – sara Mar 13 '20 at 09:45
  • @sara - One idea, how working change `df['c2'] = df['c1'].map(d1)` to `df['c2'] = df['c1'].astype(str).map(d1)` ? – jezrael Mar 13 '20 at 09:51
  • does that change values? coz if i print d1, all values got mapped to normal.. how does that change after mapping? – sara Mar 13 '20 at 10:15
  • @sara - It was idea if is necessary change column values to strings. But if still not working I guess some data related probl;em. – jezrael Mar 13 '20 at 10:16
  • @sara - Are data confidental? – jezrael Mar 13 '20 at 10:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209561/discussion-between-sara-and-jezrael). – sara Mar 13 '20 at 10:20