pandas ,与数据框行条目的args一起应用 [英] pandas, apply with args which are dataframe row entries
本文介绍了 pandas ,与数据框行条目的args一起应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有两列"A"和"B"的熊猫数据框"df",我有一个带有两个参数的函数
I have a pandas dataframe 'df' with two columns 'A' and 'B', I have a function with two arguments
def myfunction(B, A):
# do something here to get the result
return result
并且我想使用"apply"功能逐行将其应用于df
and I would like to apply it row-by-row to df using the 'apply' function
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']作为整个系列!不只是该系列中的行条目.
whats happening here, it seems it takes df['A'] as the whole series! not just the row entry from that series as required.
推荐答案
我认为您需要:
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
这篇关于 pandas ,与数据框行条目的args一起应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文