Is there an elegant way to map an alias to its real entity name in a connected data file?

Viewed 85

I have a big csv file containing connected data such as:

Source,Target
a,token
b,token2
c,token3
d,j
e,k
f,l
token,g
token2,h
token3,i

the structure of the file is mixed, so the rows where the relation is

a,token
b,token2
c,token3

do not identify specific relations in the network graph, but instead define aliases to which the entities a, b and c are mapped.

In the rest of the file, i have standard relations (d,j; e,k; f,l) but also relations where the real name of the entity is replaced by its alias:

token,g
token2,h
token3,i

Currently, I am looping over the file with ugly 'for' loops and in such a way I am able to map the relations in the desired way and to get:

a,g
b,h
c,i

but it's not an elegant way and, perhaps, heavy on my cpu.

Is there any built-in function (maybe in pandas) or some elegant and quick way (few lines of code) to map the file as desidred in Python?

2 Answers
data = [
    ['a', 'token'],
    ['b', 'token2'],
    ['c', 'token3'],
    ['d', 'j'],
    ['e', 'k'],
    ['f', 'l'],
    ['token', 'g'],
    ['token2', 'h'],
    ['token3', 'i']
]
df = pd.DataFrame(data, columns=['Source', 'Target'])
source_to_target = {row.Source: row.Target for row in df.itertuples()}
df.loc[:, 'AliasedTarget'] = df.loc[:, 'Target'].apply(lambda x: source_to_target.get(x, x))
print(df.head()) 

  Source  Target AliasedTarget
0      a   token          g
1      b  token2          h
2      c  token3          i
3      d       j          j
4      e       k          k

IIUC, you can try:

  1. Fetch the common elements from source / target.
  2. Replace the value of common elements in target with the required values.
  3. Delete the rows with common elements.
import numpy as np

common_elements = np.intersect1d(df.Source.values, df.Target.values)
df.Target = df.Target.replace(dict(df[df.Source.isin(common_elements)].values))
df = df[~df.Source.isin(common_elements)]
OUTPUT:
  Source Target
0      a      g
1      b      h
2      c      i
3      d      j
4      e      k
5      f      l
Related