0

I have an array called arr1

arr1 
Out[23]: 
[('001',
  '249',
  '580',
  'E930'),
 ('001',
  '270',
  '290',
  '780'),
 ('030',
  '110',
   '789',
  '990',
  '996',
  'E8779',
  'E9349',
  'V10',
  'V85'),
 ('030',
  '070',
  '249',
  '270',
  '360',
  '400',
  '450',
  '490',
  'V10',
  'V40'),
 ('400', '580', '990', '916'),
 ('030',
  '270',
  '600',
  '725',
  '780',
  '990',
  '996',
  'V10'),
 ('110',
  '200',
  '249',
  '340',
  '400',
  '410',
  '420',
  '510'),
 ('400', '430'),
 ('210', '400', '420', '450', '720', 'V10'),
 ('070', '280', '286', '290', '300', '450', '570')]

and I have a dataframe called df_map

df_map
Out[24]: 
             Old        New

1             001       A91
2             780       B63
3             E8779     C72
4             V85       D02
5             450       E82
            ...       ...  
999            070      F28

I want to swap Old values in the array with the new values in the dataframe

Here is my code

for x in arr1:
    for y in x:
        y=df_map[(df_map["Old"]==y)]["New"]
        

but when I check arr1 values they still the orginal

I want arr1 values to be the new values in df_maps

3
  • @HenryEcker Old values in df_map to be replaced with New Commented Apr 25, 2021 at 0:54
  • "I check arr1 values they still the original" makes it seem like you're trying to replace the values in arr1. Commented Apr 25, 2021 at 0:56
  • yes I want arr1 values to be the new values in df_maps Commented Apr 25, 2021 at 0:57

1 Answer 1

3

This can be done by converting your dataframe into a dictionary, then just mapping a function which replaces from the dictionary over each tuple in the list:

df_map = pd.DataFrame({'Old': ['001', '780', 'E8799', 'V85', '450', '070'], 
                       'New': ['A91', 'B63', 'C72',   'D02', 'E82', 'F28']})
arr1 = [
 ('001', '430'),
 ('210', '780', '420', '450', 'E8799', 'V10'),
 ('070', 'V85', '286', '290', '780', '450', '570')
]

m = df_map.set_index('Old')['New'].to_dict()
out = [tuple(map(lambda v:m.get(v, v), t)) for t in arr1]

Output:

[
 ('A91', '430'),
 ('210', 'B63', '420', 'E82', 'C72', 'V10'),
 ('F28', 'D02', '286', '290', 'B63', 'E82', '570')
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.