gpt4 book ai didi

python - pandas groupby 并更新一列中的值大于另一列中的值的次数总和

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:51 24 4
gpt4 key购买 nike

我有一个以下格式的数据集

df = pd.DataFrame([[1, 'Label1', 0, 8, 2], [1, 'Label3', 0, 20, 5], [2, 'Label5', 1, 20, 2], [2, 'Label4', 1, 11, 0], 
[5, 'Label2', 0, 0, -4],[1, 'Label2', 1, 8, 2], [2, 'Label5', 0, 20, 5], [3, 'Label2', 1, 20, 2], [4, 'Label4', 0, 1, 0],
[5, 'Label3', 0, 1, -4],[1, 'Label3', 1, 8, 2], [2, 'Label4', 0, 20, 5], [3, 'Label1', 1, 20, 2], [4, 'Label3', 0, 1, 0],
[5, 'Label4', 0, 1, -4],[1, 'Label4', 1, 8, 2], [2, 'Label3', 0, 20, 5], [3, 'Label3', 1, 20, 2], [4, 'Label5', 0, 1, 0],
[5, 'Label5', 0, 1, -4]],
columns=['ID', 'Label', 'Status', 'Coeff', 'result'])

cm = {'TP': 0,'FP': 0}

对于 df 中的每个 ID,我想查找当 时列 Coeff 大于 Result 的次数Status 列为 1。如果此计数大于 3,则 TP 应增加 1,如果小于 3,则 FP 应增加1.

示例:当ID为1111且Status为1时,如果Coeff列大于Result列对于该特定 ID 两次,则 FP 必须增加 1。

我尝试为每个 ID 添加一个名为 count 的新列,并在每次列 Coeff 大于 Result 时将值分配为 1。

for ID in df.groupby('ID'): 
df.loc[(df['Coeff'] > df['Result']), 'count'] = 1
df_new = list(df[['ID','count']].groupby(df['ID']))

然后我想到了查找count里面是否有数字1。如果是,则增加 TP。否则,增加 FP

但是我没能实现。

如何获得所需的结果?

最佳答案

对屏蔽比较进行简单的分组操作应该可以:

v = df.Coeff.gt(df.result).where(df.Status.astype(bool)).groupby(df.ID).sum()

或者(保留dtype=int,谢谢 piR!),

v = df.Coeff.gt(df.result).where(df.Status.astype(bool), 0).groupby(df.ID).sum()

v   # second expression result

ID
1 3
2 2
3 3
4 0
5 0
dtype: int64

现在,

cm['TP'] = v.gt(3).sum()
cm['FP'] = v.lt(3).sum()

详细信息
df.Coeff.gt(df.result) 返回一个掩码。现在,隐藏所有 df.Status 不为 1 的值。这是使用 (df.Coeff > df.result).where(df.Status.astype(bool)) 完成的。最后,获取此屏蔽结果,并根据 ID 进行分组,然后求和以获得结果。

关于python - pandas groupby 并更新一列中的值大于另一列中的值的次数总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49183759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com