You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于DataFrame单列多条件统计对应唯一ID的数量?

你可以基于已生成的透视表继续按以下步骤操作:

  1. 先将透视表中的NaN填充为0,方便后续判断
  2. 给每个ID打对应的品牌组合标签
  3. 统计各标签的数量,调整列名和排序即可得到目标结果

基于现有透视表的实现代码

# 填充空值为0
df_pivot = df_pivot.fillna(0)

# 生成品牌组合标签
def assign_tag(row):
    if row["A"] > 0 and row["B"] == 0:
        return "A Only"
    elif row["B"] > 0 and row["A"] == 0:
        return "B Only"
    return "A and B"

df_pivot["brands"] = df_pivot.apply(assign_tag, axis=1)

# 统计各标签的ID数量,按要求调整顺序
result = df_pivot["brands"].value_counts().reindex(["A Only", "B Only", "A and B"]).reset_index()
result.columns = ["brands", "count_of_unique_ID"]

更简便的一步到位实现(无需提前生成透视表)

也可以直接按ID分组聚合品牌信息,直接得到结果:

result = df.groupby("ID")["Brand"].apply(lambda x: " and ".join(sorted(x.unique())))\
           .replace({"A": "A Only", "B": "B Only"})\
           .value_counts()\
           .reindex(["A Only", "B Only", "A and B"])\
           .reset_index()
result.columns = ["brands", "count_of_unique_ID"]

两种方法输出的result都完全符合你的预期要求。

内容的提问来源于stack exchange,提问作者kcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:54:04