pandas apply() function passes parameters, and solves TypeError: xxxx() takes 2 positional arguments but 3 were given error

Solution

The reasonable approach is as follows:

import pandas as pd


def add_symbol(series: pd.Series, symbol): # symbol 为需要的参数
    series['列名'] += symbol
    return series


list_data = ['a', 'b', 'c', ]
df = pd.DataFrame(data=list_data, columns=['列名'])
df = df.apply(add_symbol, axis=1, args=("--",)) # 这里把 "--" 作为 symbol 参数

Problem resolution

In apply()If argsthe parameters did not write the final ,will be given! ! ! !

For example, the following method will report an error:

import pandas as pd


def add_symbol(series: pd.Series, symbol): # symbol 为需要的参数
    series['列名'] += symbol
    return series


list_data = ['a', 'b', 'c', ]
df = pd.DataFrame(data=list_data, columns=['列名'])
df = df.apply(add_symbol, axis=1, args=("--")) # 这里把 "--" 作为 symbol 参数

Guess you like

Origin blog.csdn.net/weixin_35757704/article/details/114538336