Suppose I have a list that holds a list of column names:
columns = [
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75',
'Village President V Black Earth', 'Village Trustee V Black Earth',
'Unnamed: 78', 'Unnamed: 79', 'Village President V Blue Mounds',
'Village Trustee V Blue Mounds', 'Unnamed: 82',
'Village Trustee V Cottage Grove', 'Unnamed: 94', 'Unnamed: 95',
'Village President V Cross Plains', 'Village Trustee V Cross Plains',
'Unnamed: 98', 'Unnamed: 99'
]
And I want to find all Unnamed: XX
values and replace them consecutively with the first valid string. For example:
Input:
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75'
Output:
'Village Trustee V Belleville', 'Village Trustee V Belleville', 'Village Trustee V Belleville'
For this I have a function:
def rename_unnamed(columns):
current_value = None
pattern = re.compile(r'^Unnamed:\s\d+$')
for column_index, column in enumerate(columns):
if re.match(pattern, column):
columns[column_index] = current_value
else:
current_value = column
return columns
Which does the job pretty fine, however, I was wondering if this could be improved and/or simplified, as this looks like a mouthful for rather a simple task.