python函数的可选参数字符串和数据框

时间:2019-09-26 11:01:27

标签: python pandas function

我具有执行多项任务的功能。我需要将可选的字符串/变量和可选的数据帧与其他值一起传递。 例如,这是我的功能。

def main(df,option=None,type=None, *args)
    if type == "cars":
       #multiple functions..
       df      = function1(df)
       results = function2(df)
       if option =="ex":
          results = function4(results)
       elif option =="CDS":
           result  = function5(results)
    elif type == "buses":
         df2 = pd_read_csv("data2",sep="\t",header=0) # This is the optional data frame I wannna pass
         def func3(df2,results,df):
             result["col3"] =pd.merge(df2,df, on="col1")
             return result
         if option =="ex":
            results = function4(results)
         elif option =="CDS":
            result  = function5(results)
     return(result)

我已经有两个mainoption传递给我的函数type的两个可选变量。现在,我需要再传递一个可选变量df2。但是我不知道该怎么办。上面的示例是我主要功能的模板。在这里,我想将df2添加到main()并在elif的第一个buses循环中使用它。

任何建议或帮助都将受到赞赏

2 个答案:

答案 0 :(得分:2)

您可以在主函数中使用* args参数将可选参数(例如df2)传递为:

def main(df,option=None,type=None, *args):
    df2=args[0]    # here you will get the df2

# call main function as
main(df,option,type,df2)

OR

您还可以使用 kwargs 传递关键字可选参数,例如,

def main(df,option=None,type=None, **kwargs):
    df2=kwargs['df2']   # here you will get the df2

# call main function as
main(df,option,type,df2=df2)

希望这会有所帮助!

答案 1 :(得分:1)

看起来像您需要的。

    public class CategoryModel
    {
        public string Label { get; set; }
        public List<ItemGroupModel> ItemGroups { get; set; }
    }

    public class ItemGroupModel
    {
        public string Label { get; set; }
        public List<ItemModel> Items { get; set; }
    }

    public class ItemModel
    {
        public string Label { get; set; }
    }