代码在编写时有效,但在定义时无效

时间:2020-10-16 14:08:35

标签: python pandas function

在这里和在编程世界中我都是新手,所以这可能是一个很简单的问题,但是我不明白。 我使用Jupyter Notebook。

我想对某些分数求和,当我正常键入代码时,它可以正常工作:

select_df = df.filter(like = 'ABC')
select_df = select_df.loc[(df.REF == '000')]
select_df.sum(axis=1)

但是当我定义函数并像这样尝试时,它不起作用:

def sum_score(a, b):
    select_df = df.filter(like = a)
    select_df = select_df.loc[(df.REF == b)]
    select_df.sum(axis=1)

sum_score('ABC', '000')

当我输入为:

print(sum_score('ABC', '000'))

它只是说

3 个答案:

答案 0 :(得分:1)

您必须从函数中return进入df:

def sum_score(qu, vc):
    select_df = df.filter(like = qu)
    select_df = select_df.loc[(df.REF == vc)]
    select_df.sum(axis=1)
    return select_df # Return the df

然后像这样调用函数:

print(sum_score('ABC', 'V000'))

答案 1 :(得分:-1)

这将起作用:

def sum_score(qu, vc):
    select_df = df.filter(like = qu)
    select_df = select_df.loc[(df.REF == vc)]
    return select_df.sum(axis=1)

print(sum_score('ABC', 'V000'))

答案 2 :(得分:-1)

函数不返回任何结果。 您可以在函数的最后一行添加return以获取结果并使用/打印

def sum_score(qu, vc):
    select_df = df.filter(like = qu)
    select_df = select_df.loc[(df.REF == vc)]
    return select_df.sum(axis=1)

u可以得到如下结果:

sum_res = sum_score('ABC', 'V000')
print(sum_res)

print(sum_score('ABC', 'V000'))