【问题标题】:How to do calculation in a column in pandas and append the result to a list如何在熊猫的列中进行计算并将结果附加到列表中
【发布时间】:2020-06-05 03:04:33
【问题描述】:

这是我的代码

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

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

【问题讨论】:

  • 假设这是一个 pandas 数据框,更改您的函数以将一行作为输入变量(而不是 df)。然后使用 apply 来获得一系列结果。然后将系列转换为列表。
  • 您的预期结果是什么?

标签: python pandas list dataframe


【解决方案1】:

使用DataFrame.groupby:

df['count'] = df.groupby(['y','x'])['x'].transform('size')
print(df)
   y  x  count
0  1  0      1
1  0  1      1
2  1  1      2
3  1  1      2

如果你想要一个列表:

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

#[0, 1, 1, 2]

如果我是你,我会使用 dict

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

【讨论】:

    【解决方案2】:

    您可以将列表本身作为函数的return 输出:

    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
    

    【讨论】:

    • 为什么是布尔索引而不是 symply sum?
    【解决方案3】:

    除非我误解了您的目标,否则您似乎正在尝试将混淆矩阵作为列表。您可以使用sklearn 中的confusion_matrix 函数,而不是重新发明轮子:

    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]                                                                                                                                                                                               
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 2019-10-01
      • 2021-03-21
      • 2018-01-03
      • 2017-01-29
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多