简体   繁体   English

创建一个带有未定义数量参数的定义

[英]Creating a definition that takes undefined number of parameters

What would be the best method of turning a code like below to be able to accept as many dataframes as we would like?将如下代码转换为能够接受我们想要的尽可能多的数据帧的最佳方法是什么?

def q_grab(df, df2, df3, q): #accepts three dataframes and a column name. Looks up column in all dataframes and combine to one
    data = df[q], df2[q], df3[q]
    headers = [q+"_1", q+"_2", q+"_3"]
    data2 = pd.concat(data, axis = 1, keys=headers)
    return data2

q = 'covid_condition'
data2 = q_grab(df, df2, df3, q) #If I run function pid_set first, it will create new df based on pID it looks like

One approach is to use * operator to get a list of arguments (but name your final argument, so it isn't part of the list):一种方法是使用 * 运算符来获取参数列表(但命名您的最终参数,因此它不是列表的一部分):

Something like this:像这样的东西:

def q_grab(*dfs, q=None): # q is a named argument to signal end of positional arguments
    data = [df[q] for df in dfs]
    headers = [q+"_"+str(i) for i in range(len(dfs))]
    data2 = pd.concat(data, axis = 1, keys=headers)
    return data2

q = 'covid_condition'
data2 = q_grab(df, df2, df3, q=q)    

A probably cleaner alternative, is to go ahead and pass a list of dataframes as the first argument:一个可能更简洁的替代方法是继续传递数据帧列表作为第一个参数:

 def q_grab(dfs,q):
   

called with:调用:

 data2 = q.grab([df,df2,df3], q)

using the function code as above使用上面的函数代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM