[英]Pandas Apply Function with Multiple **Kwarg Arguments
Is there a way to use pandas.apply with a variable number of multiple columnar arguments? 有没有一种方法可以将pandas.apply与可变数量的多个柱状参数一起使用? For example, say I have this data frame:
例如,说我有这个数据框:
df = pd.DataFrame({'A':['a','b','c'],
'B':['a','b','c'],
'C':['a','b','c'],
'D':['a','b','c']})
I want to write a function that concatenates columns to produce a new column - very similar to this SO question . 我想编写一个将列连接起来以产生新列的函数-非常类似于此SO问题 。 So a two column example would be:
因此,两列示例将是:
def dynamic_concat_2(df, one, two):
return df[one]+df[two]
I use the function like so 我像这样使用功能
df['concat'] = df.apply(dynamic_concat2, axis=1, one='A',two='B')
Now the difficulty that I cannot figure out is how to do this for an unknown dynamic amount of columns. 现在,我无法弄清的困难是如何对未知数量的动态列执行此操作。 Is there a way to generalize the function usings **kwargs?
有没有一种方法可以使用** kwargs来泛化功能? So it could be 1-n columns to concatenate?
所以可能是1-n列要连接?
Additional context: This is a simple example of a larger problem to dynamically calculate row level data. 其他上下文:这是动态计算行级数据的较大问题的简单示例。 A unknown number of columns have data that specifies a query to a database - this gets fed into a query and returns a value.
数量未知的列包含指定对数据库的查询的数据-它将输入查询并返回值。 I've written some truly inflexible horribly un-pythonic solutions (think for loops going through each row of data) that haven't worked.
我已经写了一些行不通的真正僵化的可怕的非Python解决方案(考虑遍历每行数据的循环)。 I'm hoping use of a df.apply can python-ify things.
我希望使用df.apply可以对内容进行python验证。
If I understand your question, it seems to me that the easiest solution would be to pick the columns from your dataframe first, then apply a function that concatenates all columns. 如果我理解您的问题,在我看来,最简单的解决方案是首先从数据框中选择列,然后应用连接所有列的函数。 This is just as dynamic, but a lot cleaner, in my opinion.
我认为这是动态的,但干净得多。
For example, using your data above: 例如,使用上面的数据:
cols = ['A', 'B', 'C']
df['concat'] = df[cols].apply(''.join, axis=1)
Such that 这样的
>>> df
A B C D concat
0 a a a a aaa
1 b b b b bbb
2 c c c c ccc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.