Python 如何在pandas中的列中进行计算并将结果附加到列表中

Python 如何在pandas中的列中进行计算并将结果附加到列表中,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,这是我的密码 def calculate_TP(df): countTP=0 countFP=0 countTN=0 countFN=0 conf_lst=[] if df['y']==1 and df['x']==1: countTP+=1 elif df['y']==0 and df['x']==1: countFP+=1 elif df['y']==1 and df['x']==0:

这是我的密码

def calculate_TP(df):
    countTP=0
    countFP=0
    countTN=0
    countFN=0
    conf_lst=[]
    if df['y']==1 and df['x']==1:
        countTP+=1
    elif df['y']==0 and df['x']==1:
        countFP+=1
    elif df['y']==1 and df['x']==0:
        countFN+=1
    else:
        countTN+=1
我必须将其应用于数据帧,无论得到什么结果,我都必须附加到列表中

conf_lst.append(countTP,countFP,countTN,countFN)
我该怎么做? 我的数据帧是这样的

y  x
1  0
0  1
1  1
1  1
我必须应用上述函数,然后将输出更改为列表

使用:

如果您想要列表:

df.groupby(['y','x'])['x'].size().unstack(fill_value=0).stack().tolist()

#[0, 1, 1, 2]
如果我是你,我会用一个口述词

df.groupby(['y','x'])['x'].size().unstack(fill_value=0).stack().to_dict()

#{(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 2}
我们还可以做:

c = df['x'].ne(df['y'])
print(df.all(axis=1).sum())
print((~df.any(axis=1)).sum())
print(c.mul(df['x']).sum())
print(c.mul(df['y']).sum())


2
0
1
1

您可以将列表本身输出为函数的
返回值

def calculate_TP(df):
    countTP = len(df[(df['y']==1) & (df['x']==1)])
    countFP = len(df[(df['y']==0) & (df['x']==1)])
    countFN = len(df[(df['y']==1) & (df['x']==0)])
    countTN = len(df[(df['y']==0) & (df['x']==0)])
    conf_lst = [countTP,countFP,countFN,countTN]
    return conf_lst

除非我误解了你的目标,否则看起来你在试图得到一个混乱矩阵作为列表。您可以使用
sklearn
中的功能,而不是重新发明轮子:

from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = confusion_matrix(df.x, df.y).ravel()
conf_list = [tp, fp, tn, fn]

In [9]: conf_list                                                                                                                                                                                                  
Out[9]: [2, 1, 0, 1]                                                                                                                                                                                               

假设这是一个数据帧,将函数更改为将行作为输入变量(而不是df)。然后使用apply获得一系列结果。然后将序列转换成一个列表。你期望的结果是什么?为什么是布尔索引而不是辛和?
from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = confusion_matrix(df.x, df.y).ravel()
conf_list = [tp, fp, tn, fn]

In [9]: conf_list                                                                                                                                                                                                  
Out[9]: [2, 1, 0, 1]