在pandas中向apply()传递变量

2024-09-25 18:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法正确地将函数应用于数据帧的语法。我试图在dataframe中创建一个新列,方法是将另外两个列中的字符串连接起来,并传入一个分隔符。我知道错误了

TypeError: ("apply_join() missing 1 required positional argument: 'sep'", 'occurred at index cases')

如果我在apply\u join()函数调用中添加sep,也会失败:

^{pr2}$

一。在

import pandas as pd
from io import StringIO

tibble3_csv = """country,year,cases,population
Afghanistan,1999,745,19987071
Afghanistan,2000,2666,20595360
Brazil,1999,37737,172006362
Brazil,2000,80488,174504898
China,1999,212258,1272915272
China,2000,213766,1280428583"""
with StringIO(tibble3_csv) as fp:
    tibble3 = pd.read_csv(fp)
print(tibble3)

def str_join_elements(x, sep=""):
    assert type(sep) is str
    return sep.join((str(xi) for xi in x))

def unite(df, cols, new_var, combine=str_join_elements):

    def apply_join(x, sep):
        joinstr = str_join(x, sep)
        return pd.Series({new_var[i]:s for i, s in enumerate(joinstr)})

    fixed_vars = df.columns.difference(cols)
    tibble = df[fixed_vars].copy()
    tibble_extra = df[cols].apply(apply_join)

    return pd.concat([tibble, tibble_extra], axis=1) 
table3_again = unite(tibble3, ['cases', 'population'], 'rate', combine=lambda x: str_join_elements(x, "/"))
print(table3_again)

Tags: csvimportdfreturndefelementsseppd
2条回答

当您有多个参数时使用lambda,即

df[cols].apply(lambda x: apply_join(x,sep),axis=1)

或者在args参数的帮助下传递参数,即

^{pr2}$

只需将其添加到apply语句中:

tibble_extra = df[cols].apply(apply_join, sep=...)

此外,还应指定轴。没有它也许可以工作,但它是防止错误的好习惯:

^{pr2}$

相关问题 更多 >