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

如何在Pandas中根据两列条件识别特定评分的用户ID?

识别跨应用打5星与1星的用户ID解决方案

需求:从包含1,050,000行数据的DataFrame中,找出**在不同应用分别打出5星和1星(顺序不限)**的用户ID,并为这些用户的所有记录新增User0n1列标记为1,其余记录标记为0。

示例输入

ID  Star  App_Name
0    41a-Z451     5         A
1    40591758     5         A
2    41128444     5         R
3    40537354     2         H
4    41a-Z451     1         B
5    40552356     1         I
6    413lll95     4         K
7    40htt506     5         A
8    41322993     3         C
9    414ju239     4         D

期望输出

ID  Star  App_Name    User0n1
0    41a-Z451     5         A          1
1    40591758     5         A          0
2    41128444     5         R          0
3    40537354     2         H          0
4    41a-Z451     1         B          1
5    40552356     1         I          0
6    413lll95     4         K          0
7    40htt506     5         A          0
8    41322993     3         C          0
9    414ju239     4         D          0

高效解决方案(适配百万级数据)

使用Pandas的分组与集合操作,避免逐行循环,保证处理效率:

import pandas as pd

# 读取你的数据(替换为实际数据路径)
df = pd.read_csv("your_data.csv")

# 1. 筛选出星级为1或5的记录(其他星级不影响判断)
filtered_records = df[df['Star'].isin([1, 5])]

# 2. 按用户ID分组,获取每个用户的(星级, 应用)配对集合
user_star_app = filtered_records.groupby('ID').apply(
    lambda x: set(zip(x['Star'], x['App_Name']))
)

# 3. 判断用户是否符合条件:同时有5星和1星,且对应的应用不同
def check_condition(pairs):
    # 先确认用户同时打了5星和1星
    has_5 = any(star == 5 for star, app in pairs)
    has_1 = any(star == 1 for star, app in pairs)
    if not (has_5 and has_1):
        return False
    # 分离5星和1星对应的应用,检查是否无重叠(即来自不同应用)
    apps_for_5 = {app for star, app in pairs if star == 5}
    apps_for_1 = {app for star, app in pairs if star == 1}
    return apps_for_5.isdisjoint(apps_for_1)

# 提取符合条件的用户ID列表
target_users = user_star_app[user_star_app.apply(check_condition)].index

# 4. 为原DataFrame新增标记列
df['User0n1'] = df['ID'].isin(target_users).astype(int)

# 输出或保存结果
print(df)
# df.to_csv("result.csv", index=False)

方案说明

  • 仅筛选星级为1/5的记录,减少后续计算量
  • 用集合存储用户的星级-应用配对,快速判断是否存在跨应用的5星和1星
  • 基于Pandas的向量化操作与分组功能,处理百万级数据效率远高于循环遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:10:30