Look Up And Replace Values In A List (pandas)
I have a list z = ['111111','222222','333333','4444444'] and I want to look up each item in z and replace it with the equivalent value in stored in my dataframe 'data', which has
Solution 1:
You can create a mapping using a dictionary comprehension:
d = {k: v for k, v inzip(df.old_ids, df.new_ids)}
z_new = [d.get(k, k) for k in z]
>>> z_new
['121212', '202020', '303030', '4444444']
Note that the d.get(k, k)
defaults to the original value if no lookup value is found in df.old_ids
.
Solution 2:
I would use Pandas power for that:
In [109]: z = ['111111','222222','333333','4444444']
In [110]: df = pd.DataFrame({'z': z})
In [111]: data
Out[111]:
new_ids old_ids
01212121111111202020222222230303033333334040404444444
In [112]: df
Out[112]:
z
01111111222222233333334444444
In [118]: dict(data[['old_ids','new_ids']].values)
Out[118]:
{'111111': '121212',
'222222': '202020',
'333333': '303030',
'4444444': '404040'}
In [119]: df.replace(dict(data[['old_ids','new_ids']].values), inplace=True)
In [120]: df
Out[120]:
z
0121212120202023030303404040
Solution 3:
Something like this should work:
for index, i in enumerate(z):
if i in old_numbers:
z[index] = new_numbers[old_numbers.index(i)]
This won't work if you have duplicates in old_numbers, as index only returns the first match.
Post a Comment for "Look Up And Replace Values In A List (pandas)"