python - Pandas ,适用于作为数据框行条目的参数

标签 python pandas apply args

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

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

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

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

但是我得到了错误

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

这是怎么回事,好像把df['A']当成整个系列了!不仅仅是该系列的行条目。

最佳答案

我认为你需要:

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

或者:

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

关于python - Pandas ,适用于作为数据框行条目的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39814416/

相关文章:

python - 如何在打印语句后取消换行符?

python - 在python中计算积分

python - 如何用Python绘制结构化数据文件?

python - 计算值并将值放入 M​​ultiIndex Pandas DataFrame 的二级列中

common-lisp - 如何减少 Common Lisp 中的 bool 值列表?

python - wxPython : How to refresh and draw on wx. 来自不相关类的框架

python - Linux - IPython 中的换行符

python - 如何根据条件将值附加到 Pandas 数据框中单个单元格中的列表

javascript - 从另一个函数返回函数参数

r - 将函数应用于 R 中 data.frame 中的组