You can use re.sub passing lambda for the replacement text. You can use the pattern (.*?)\.mean\(\), and surround the captured group with parenthesis, and starting it with average
>>> import re
>>> text='m863991.mean()'
>>> re.sub('(.*?)\.mean\(\)', lambda x: 'average('+x.group(1)+')', text)
'average(m863991)'
But to be specific, as you have mentioned the criteria for these values, you can use the pattern (m\d{5}[12])\.mean\(\) for the values that start with m, 5 digits in the middle, and ending with 1 or 2, and .mean() at last.
>>> re.sub('(m\d{5}[12])\.mean\(\)', lambda x: 'average('+x.group(1)+')', text)
'average(m863991)'