How can I pass along parameters to a mapper function in pandas.DataFrame.rename
? The example below uses a mapper function test
. I want to change it’s behavior based on an additional parameter that I pass along.
def test(x): return "A" + x df.rename(mapper=test, axis='columns')
In this example, the mapper function appends an "A"
to each column name. I want the mapper not always to append an "A"
but a character that I give as parameter in the function call. So my question is: how can I pass along additional parameters to the function test
?
Advertisement
Answer
IIUC, you can use functools.partial
:
import pandas as pd from functools import partial print(pd.__version__) #0.23.4 df = pd.DataFrame({"col1": ['a', 'b', 'c'], "col2": [1, 2, 3]}) def test(col, x): return x + col df.rename(mapper=partial(test, x="abc_"), axis='columns') # abc_col1 abc_col2 #0 a 1 #1 b 2 #2 c 3