Home > Mobile >  transform a pandas dataframe into a list by comparing another list
transform a pandas dataframe into a list by comparing another list

Time:08-21

I created a dataframe like this

    Adresses
0   Addr_0
1   Addr_1
2   Addr_2
3   Addr_3

also I have this list

[[(0, 1),
  (1, 3),
  (3, 2),
  (2, 0),]]

how can I create a list like this:

[[(Addr_0, Addr_1),
  (Addr_1,Adrr_3),
  (Addr_3,Addr_2),
  (Addr_2,Addr_0),]]

Thanks a lot!

CodePudding user response:

You can try numpy indexing

out = df['Adresses'].values[np.array(lst)]
print(out)

[[['Addr_0' 'Addr_1']
  ['Addr_1' 'Addr_3']
  ['Addr_3' 'Addr_2']
  ['Addr_2' 'Addr_0']]]

CodePudding user response:

You can try:

df = pd.DataFrame({'Adresses':['Addr_0', 'Addr_1', 'Addr_2', 'Addr_3']})
lst = [[(0, 1), (1, 3), (3, 2), (2, 0),]]
lst.sort()
[[(x, f'Addr_{(lst[0][int(x.split("_")[-1])])[-1]}') for x in df.Adresses]]

Output:

[[('Addr_0', 'Addr_1'),
  ('Addr_1', 'Addr_3'),
  ('Addr_2', 'Addr_2'),
  ('Addr_3', 'Addr_0')]]
  • Related