简体   繁体   English

使用带参数的映射器 function 重命名 dataframe 列

[英]Rename dataframe columns with a mapper function that takes parameters

How can I pass along parameters to a mapper function in pandas.DataFrame.rename ?如何将参数传递给 pandas.DataFrame.rename 中的映射器pandas.DataFrame.rename The example below uses a mapper function test .下面的示例使用映射器 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.在此示例中,映射器 function 将"A"附加到每个列名。 I want the mapper not always to append an "A" but a character that I give as parameter in the function call.我希望映射器不总是 append 一个"A" ,而是我在 function 调用中作为参数给出的一个字符。 So my question is: how can I pass along additional parameters to the function test ?所以我的问题是:如何将其他参数传递给 function test

IIUC, you can use functools.partial : IIUC,您可以使用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

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:除了自定义test function,您还可以使用内置的lambda function 作为映射器 function 并传递参数以重命名 pandas.8827980.6318 中的dataframe列,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM