Python中基于分组与条件创建DataFrame的remove列需求
为DataFrame新增布尔列"remove"实现按规则保留单行
需求说明
现有如下DataFrame,需新增布尔型列remove:每个url仅保留一行,保留优先级规则为:
- 优先保留
score更高的行; - 若
score相同,track为gre或tca的行优先于oke; - 若
track也相同,保留size更大的行。remove值为True表示该行需删除,False表示保留。
原始DataFrame
| name | age | track | score | size | url | url_count | |
|---|---|---|---|---|---|---|---|
| 0 | timmy | 10 | gre | 0.982 | 41 | target.com | 2 |
| 1 | chester | 12 | tca | 0.251 | 12 | michaels.com | 3 |
| 2 | trixie | 10 | oke | 0.0879 | 15 | macys.com | 2 |
| 3 | aj | 9 | gre | 0.985 | 20 | michaels.com | 3 |
| 4 | cosmo | 150 | tca | 0.982 | 328 | target.com | 2 |
| 5 | wanda | 145 | gre | 0.879 | 550 | macys.com | 2 |
| 6 | jorgen | 500 | oke | 0.432 | 51 | michaels.com | 3 |
解决方案代码
import pandas as pd # 构造原始数据 data = [ ["timmy", 10, "gre", 0.982, 41, "target.com", 2], ["chester", 12, "tca", 0.251, 12, "michaels.com", 3], ["trixie", 10, "oke", 0.0879, 15, "macys.com", 2], ["aj", 9, "gre", 0.985, 20, "michaels.com", 3], ["cosmo", 150, "tca", 0.982, 328, "target.com", 2], ["wanda", 145, "gre", 0.879, 550, "macys.com", 2], ["jorgen", 500, "oke", 0.432, 51, "michaels.com", 3] ] df = pd.DataFrame(data, columns=["name", "age", "track", "score", "size", "url", "url_count"]) # 为track设置优先级权重:gre/tca权重为1,oke为0,用于排序 df["track_weight"] = df["track"].map({"gre":1, "tca":1, "oke":0}) # 按url分组,每组内按规则排序后标记是否为保留行 df["remove"] = ( df.groupby("url", group_keys=False) .apply(lambda g: g.sort_values(by=["score", "track_weight", "size"], ascending=[False, False, False]) .reset_index(drop=True) .index != 0) ) # 删除临时权重列 df = df.drop("track_weight", axis=1) print(df)
最终结果
运行代码后得到的DataFrame如下:
| name | age | track | score | size | url | url_count | remove | |
|---|---|---|---|---|---|---|---|---|
| 0 | timmy | 10 | gre | 0.982 | 41 | target.com | 2 | True |
| 1 | chester | 12 | tca | 0.251 | 12 | michaels.com | 3 | True |
| 2 | trixie | 10 | oke | 0.0879 | 15 | macys.com | 2 | True |
| 3 | aj | 9 | gre | 0.985 | 20 | michaels.com | 3 | False |
| 4 | cosmo | 150 | tca | 0.982 | 328 | target.com | 2 | False |
| 5 | wanda | 145 | gre | 0.879 | 550 | macys.com | 2 | False |
| 6 | jorgen | 500 | oke | 0.432 | 51 | michaels.com | 3 | True |
规则验证
target.com:两行score相同,track同属高优先级,size328>41,保留cosmo行;michaels.com:aj的score最高(0.985),直接保留;macys.com:wanda的score远高于trixie,保留wanda行。
所有结果均符合预设规则。
内容的提问来源于stack exchange,提问作者codingrainha
相关产品推荐
相关产品推荐

