Python, Pandas: Assign cells in dataframe to groups

Viewed 59

Good morning to everyone!

I'm hoping the title does fit in some way to my question!? I have a dataframe that looks something like this:

Dataframe (before):

id    |    name        |    position
1     |    jane doe    |    position_1
2     |    john doe    |    position_2
3     |    john smith  |    position_3

Also I'm having multiple lists of groups:

group_1 = ['position_3', 'position_18', 'position_45']
group_2 = ['position_2', 'position_9']
group_7 = ['position_1']

Now I'm wondering what is the best way to achieve another column inside my dataframe with the assigned group? For example:

Dataframe (after):

id    |    name        |    position    |    group
1     |    jane doe    |    position_1  |    group_7
2     |    john doe    |    position_2  |    group_2
3     |    john smith  |    position_3  |    group_1

Notes:

  • every position is unique and will never apear in more than one group!
2 Answers

You can create a mapping dictionary in which key is the position and value is the group name, then map this dictionary onto the column position:

dct = {'group_1': group_1, 'group_2': group_2, 'group_7': group_7}
mapping_dct = {pos:grp for grp, positions in dct.items() for pos in positions}

df['group'] = df['position'].map(mapping_dct)

>>> df

   id        name    position    group
0   1    jane doe  position_1  group_7
1   2    john doe  position_2  group_2
2   3  john smith  position_3  group_1
id=[1,2,3]
name=['jane doe','john doe','john smith']
position=['position_1','position_2','position_3']
df=pd.DataFrame({'id':id,'name':name,'position':position,})
group_1 = ['position_3', 'position_18', 'position_45']
group_2 = ['position_2', 'position_9']
group_7 = ['position_1']
dct = {'group_1': group_1, 'group_2': group_2, 'group_7': group_7}
def lookup(itemParam):
     keys=[]
     for key,item in dct.items():
         if itemParam in item:
              keys.append(key)
     return keys
 mylist=[*map(lookup,df['position'])]
 mylist=[x[0] for x in mylist]
 df['group']=mylist
 print(df.head())

 output:
   id        name    position    group
0   1    jane doe  position_1  group_7
1   2    john doe  position_2  group_2
2   3  john smith  position_3  group_1
Related