pandaps:使用apply将多个列名作为参数传递给函数

2024-10-01 07:28:51 发布

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

我只是问了下面的问题

Pandas: how can I pass a column name to a function that can then be used in 'apply'?

我得到了很好的答复。然而,这个问题还有一个延伸,我忽略了,也很好奇。在

我有一个功能:

def generate_confusion_matrix(row):
val=0
if (row['biopsy_bin']==0) & (row['pioped_logit_category'] == 0):
    val = 0   
if (row['biopsy_bin']==1) & (row['pioped_logit_category'] == 1):
    val = 1 
if (row['biopsy_bin']==0) & (row['pioped_logit_category'] == 1):
    val = 2
if (row['biopsy_bin']==1) & (row['pioped_logit_category'] == 0):
    val = 3
if row['pioped_logit_category'] == 2:
    val = 4
return val  

我想把它变成通用的:

^{pr2}$

这样我就可以把它应用到这个函数中,就像这样(这不起作用)。在

def create_logit_value(df, name_of_column):
   df[name_of_column + '_concordance'] = df.apply(lambda : general_confusion_matrix('biopsy', name_of_column + '_category'), axis=1)

问题似乎是,当你把列作为df['biochetic']传入时,你将一个序列传递给一般的\u confusion_矩阵函数,而不是在每一行传递一个值,条件语句抛出

   ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')"

我尝试过map和apply,但不确定如何将引用dataframe中列的2个参数传递给lambda语句中的函数。我想我可以使用map,但是,我如何通过它传递参数呢。我很抱歉写了两个密切相关的问题,但他们是不同的。在


Tags: of函数namedfifbincolumnval
1条回答
网友
1楼 · 发布于 2024-10-01 07:28:51

我觉得你很接近:

df = pd.DataFrame({'biopsy_bin':[0,1,0,1,0,1],
                   'pioped_logit_category':[0,0,0,1,1,1],
                   'a_category':[0,0,0,1,1,1]})
print (df)


def create_logit_value(df, name_of_column):
    df[name_of_column + '_concordance'] = df.apply(lambda x: generate_confusion_matrix(x['biopsy_bin'], x[name_of_column + '_category']), axis=1)
    return (df)

create_logit_value(df, 'a')
create_logit_value(df, 'pioped_logit')

   a_category  biopsy_bin  pioped_logit_category  a_concordance  \
0           0           0                      0              0   
1           0           1                      0              3   
2           0           0                      0              0   
3           1           1                      1              2   
4           1           0                      1              1   
5           1           1                      1              2   

   pioped_logit_concordance  
0                         0  
1                         3  
2                         0  
3                         2  
4                         1  
5                         2  

相关问题 更多 >