首页 > 解决方案 > 更改函数参数以产生多个输出时出错

问题描述

当我在函数之后取消注释这一行时(更改一个参数以获得第二个结果集):

weights2 = weights(flags, 0, .4, .3, .3, 0, .4) ## This line is the problem

我收到此错误:

TypeError:“元组”对象不可调用

输入:

import pandas as pd
import numpy as np

flags = pd.DataFrame({'Date': ['2017-11-01','2017-12-01','2018-01-01'],
                    'flag_11': [2, 2, 2],
                   'flag_12': [2, 2, 2]})

flags = flags.set_index('Date')
print(flags)

功能:

def weights(dfin, wt1, wt2, wt3, wmin06, wmin1012, wmax1012):
    dfin = pd.DataFrame(dfin)
    dfout = pd.DataFrame()
    dfcum = pd.DataFrame()
    mapping = {1:wt1,2:wt2,3:wt3}
    dfout['flag_12']=dfin['flag_12'].replace(mapping)
    dfcum['flag_12']=dfin['flag_12'].replace(mapping)
    i = 11
    conditions = [
    (dfin["flag_{}".format(i)]==1) & (wt1 > (wmax1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==1) & (wt1 < (wmin1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==1),
    (dfin["flag_{}".format(i)]==2) & (wt2 > (wmax1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==2) & (wt2 < (wmin1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==2),
    (dfin["flag_{}".format(i)]==3) & (wt3 > (wmax1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==3) & (wt3 < (wmin1012 - dfout["flag_{}".format(i+1)])),
    (dfin["flag_{}".format(i)]==3)]   
    choices = [
    (wmax1012 - dfout["flag_{}".format(i+1)]),
    (wmin1012 - dfout["flag_{}".format(i+1)]),
    (wt1),
    (wmax1012 - dfout["flag_{}".format(i+1)]),
    (wmin1012 - dfout["flag_{}".format(i+1)]),
    (wt2),
    (wmax1012 - dfout["flag_{}".format(i+1)]),
    (wmin1012 - dfout["flag_{}".format(i+1)]),
    (wt3)]
    dfout["flag_{}".format(i)] = np.select(conditions, choices)
    dfcum["flag_{}".format(i)] = np.select(conditions, choices)+dfcum["flag_{}".format(i+1)]
    dfout=dfout.iloc[:,::-1]
    dfcum=dfcum.iloc[:,::-1]
    return(dfout,dfcum)
weights = weights(flags, 0, .4, .025, .3, 0, .4)
# weights2 = weights(flags, 0, .4, .3, .3, 0, .4) ## This line is the problem
print(weights[0])
print(weights[1])

标签: python-3.xfunction

解决方案


weights = weights(flags, 0, .4, .025, .3, 0, .4)

这条线用从函数返回weights的元组遮蔽weights了函数。

当您第二次尝试调用该函数时,您正在“调用”元组,因此出现错误tuple is not callable

您必须为函数或返回值使用不同的名称,例如

calculated_weights1 = weights(flags, 0, .4, .025, .3, 0, .4)
calculated_weights2 = weights(flags, 0, .4, .3, .3, 0, .4)

推荐阅读