我有一个带有两列“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/