pandas 大熊猫,适用于数据框行条目的 args

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39814416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:07:25  来源:igfitidea点击:

pandas, apply with args which are dataframe row entries

pythonpandasapplyargs

提问by Runner Bean

I have a pandas dataframe 'df' with two columns 'A' and 'B', I have a function with two arguments

我有一个带有两列“A”和“B”的Pandas数据框“df”,我有一个带有两个参数的函数

def myfunction(B, A):
    # do something here to get the result
    return result

and I would like to apply it row-by-row to df using the 'apply' function

我想使用“应用”函数将它逐行应用于 df

df['C'] = df['B'].apply(myfunction, args=(df['A'],))

but I get the error

但我得到了错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

whats happening here, it seems it takes df['A'] as the whole series! not just the row entry from that series as required.

这里发生了什么,似乎整个系列都需要 df['A'] !不仅仅是该系列中所需的行条目。

回答by jezrael

I think you need:

我认为你需要:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6]})

print (df)
   A  B
0  1  4
1  2  5
2  3  6

def myfunction(B, A):
    #some staff  
    result = B + A 
    # do something here to get the result
    return result

df['C'] = df.apply(lambda x: myfunction(x.B, x.A), axis=1)
print (df)
   A  B  C
0  1  4  5
1  2  5  7
2  3  6  9

Or:

或者:

def myfunction(x):

    result = x.B + x.A
    # do something here to get the result
    return result

df['C'] = df.apply(myfunction, axis=1)
print (df)
   A  B  C
0  1  4  5
1  2  5  7
2  3  6  9