pandas,应用于参数,这些参数是dataframe行条目

2024-04-24 22:26:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框“df”,有两列“a”和“B”,有一个函数有两个参数

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]作为整个系列!不仅仅是那个序列中需要的行条目。


Tags: theto数据函数pandasdf参数get
1条回答
网友
1楼 · 发布于 2024-04-24 22:26:40

我认为你需要:

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

相关问题 更多 >