keeran_q789
keeran_q789

Reputation: 91

Building dictionary of unique IDs for pairs of matching strings

I have a dataframe like this

#Test dataframe
import pandas as pd
import numpy as np

#Build df

titles = {'Title': ['title1', 'cat', 'dog']}
references = {'References': [['donkey','chicken'],['title1','dog'],['bird','snake']]}

df = pd.DataFrame({'Title': ['title1', 'cat', 'dog'], 'References': [['donkey','chicken'],['title1','dog'],['bird','snake']]})
#Insert IDs for UNIQUE titles
title_ids = {'IDs':list(np.arange(0,len(df)) + 1)}

df['IDs'] = list(np.arange(0,len(df)) + 1)
df = df[['Title','IDs','References']]

enter image description here

and I want to generate IDs for the references column that looks like the data frame below. If there is a matching between the strings, assign the same ID as in the IDs column and if not, assign a new unique ID.

enter image description here

My first attempt is using the function

#Matching function
def string_match(string1,string2):
    if string1 == string2:
        a = 1
    else:
        a = 0

    return a

and to loop over each string/title combination but this gets tricky with multiple for loops and if statements. Is there a better way I can do this that is more pythonic?

Upvotes: 4

Views: 176

Answers (3)

Bushmaster
Bushmaster

Reputation: 4608

In addition to the answers this can also be done with the help of a function, apply and lambda:

id_info=dict(df[['Title','IDs']].values)
def check(title,ref):
    new_id_ = max(id_info.values())  #get latest id

    ids=[]
    for i in ref:
        if i in id_info:  #if Reference value is defined before, get its id
            new_id=id_info[i]
        else:
            new_id=new_id_ + 1 #define a new id if not defined before and update dictionary to get latest id in next steps
            new_id_+=1
            id_info.update({i:new_id})          
        ids.append(new_id)
    return ids
    
df['new_id']=df.apply(lambda x: check(x['Title'],x['References']),axis=1)
print(df)
'''
    Title   IDs References              RefIDs
0   title1  1   ['donkey', 'chicken']   [4, 5]
1   cat     2   ['title1', 'dog']       [1, 3]
2   dog     3   ['bird', 'snake']       [6, 7]


'''

Upvotes: 1

BENY
BENY

Reputation: 323326

Let us try with factorize

s = df['References'].explode()
s[:] = pd.concat([df['Title'],s]).factorize()[0][len(df['Title']):]
df['new'] = (s+1).groupby(level=0).agg(list)
Out[237]: 
0    [4, 5]
1    [1, 3]
2    [6, 7]
Name: References, dtype: object

Upvotes: 1

Code Different
Code Different

Reputation: 93181

# Explode to one reference per row
references = df["References"].explode()

# Combine existing titles with new title from References
titles = pd.concat([df["Title"], references]).unique()

# Assign each title an index number
mappings = {t: i + 1 for i, t in enumerate(titles)}

# Map the reference to the index number and convert to list
df["RefIDs"] = references.map(mappings).groupby(level=0).apply(list)

Upvotes: 2

Related Questions