gpt4 book ai didi

python - pandas 中的两个条件子句计数

转载 作者:行者123 更新时间:2023-12-03 07:54:17 24 4
gpt4 key购买 nike

我有一个看起来像这样的 df:

api_spec_id  type_of_change   label
213 Breaking NaN
213 Breaking major
213 Non-Breaking patch
345 Non-Breaking NaN
345 Non-Breaking patch
345 Non-Breaking patch
678 Breaking NaN
678 Breaking minor
678 Breaking major
123 Breaking NaN
123 Breaking NaN

我想计算 api_spec_id 的唯一编号,其中:

所有 type_of_change 均已损坏,预期输出为 2(id:678,123)

所有 type_of_change 都是不间断的,其中预期输出为 1 (id:345)

至少有一个 type_of_change 被破坏,预期输出:3 (ids:213,678,123)

至少有一个 type_of_change 是不间断的,预期输出:2 (ids:213,345)

我不确定如何实现这一目标,任何建议或想法将不胜感激。

最佳答案

可能的解决方案:

from functools import partial

grp = df.groupby("api_spec_id")

def detect(g, how, change):
if how == "all":
return g["type_of_change"].eq(change).all()
elif how == "any":
return g["type_of_change"].eq(change).any()

def get_id(df):
return df["api_spec_id"].unique().tolist()

v1 = grp.filter(partial(detect, how="all", change="Breaking")).pipe(get_id)
v2 = grp.filter(partial(detect, how="all", change="Non-Breaking")).pipe(get_id)
v3 = grp.filter(partial(detect, how="any", change="Breaking")).pipe(get_id)
v4 = grp.filter(partial(detect, how="any", change="Non-Breaking")).pipe(get_id)

输出:

print(v1) # [678, 123]
print(v2) # [345]
print(v3) # [213, 678, 123]
print(v4) # [213, 345]

关于python - pandas 中的两个条件子句计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76450952/

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