Feb-14-2020, 10:11 AM
I would solve the problem as follows:
which would be faster.
import pandas as pd data = {'id': ['aa11bc', 'bb22cd', 'cc33ef', 'dd44gh', 'ee55ij','ff66kl','gg77mn','hh88op'], 'direction': ["north, south, east, west", "north, south, east, west", "north, south, east, west", "north, south, east, west", "north, south, east, west","north, south, east, west","north, south, east, west" ,"north, south, east, west"]} df = pd.DataFrame(data, columns = ['id','direction']) def get_direction(row): mapper = {'%s%s' % (a, n): k // 2 for k, (a, n) in enumerate(zip('abcdefgh', '12345678'))} index = mapper.get(row['id'][1:3].lower()) if index is not None: return row['direction'].split(',')[index] df['position'] = df.apply(get_direction, axis=1)However,
direction
column doesn't change, this probably can be used to get completely vectorized solution of the problem,which would be faster.