2

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?

pault
  • 41,343
  • 15
  • 107
  • 149
Lorenz
  • 266
  • 1
  • 5
  • 16
  • 1
    You could probably use [`functools.partial`](https://stackoverflow.com/questions/15331726/how-does-the-functools-partial-work-in-python). Please include a [mcve] with a small sample input dataframe and the desired output. – pault Mar 19 '19 at 16:31
  • I added the mapper function. How do I need to change the mapper function and the call so that it appends "A" in one case and "B" in the other case – Lorenz Mar 19 '19 at 16:35
  • It's still not clear what your desired output is. Do you want to add `"A"` to each column? Or `"A" + x`? [How to create good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – pault Mar 19 '19 at 16:42
  • The mapper 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 a parameter to the function "test" – Lorenz Mar 19 '19 at 16:44
  • 1
    try add_prefix :-) – BENY Mar 19 '19 at 17:00

2 Answers2

2

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
pault
  • 41,343
  • 15
  • 107
  • 149
2

Instead of a custom test function, you can also use the built-in lambda function as the mapper function and pass parameters to rename dataframe columns in pandas.DataFrame.rename like this:

import pandas as pd

print(pd.__version__)
#1.4.2

df = pd.DataFrame({"col1": ['a', 'b', 'c'], "col2":[1,2,3]})

df.rename(mapper=lambda x: "abc_"+x,axis='columns')
#  abc_col1  abc_col2
#0        a         1
#1        b         2
#2        c         3
tmiener
  • 21
  • 2