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

如何筛选Pandas DataFrame中列值仅出现一次的行

筛选DataFrame中指定列值仅出现一次的行

原始DataFrame

import pandas as pd
sample_df = pd.DataFrame(columns=["A", "B"], data=[[1, "Red"], [2, "Blue"], [3, "Green"],
                                                   [4, "Red"], [5, "Blue"], [6,"Yellow"]])

输出:

A       B
0  1     Red
1  2    Blue
2  3   Green
3  4     Red
4  5    Blue
5  6  Yellow

需求

保留列B中值仅出现一次的行,期望结果:

A       B
2  3   Green
5  6  Yellow

解法一:利用value_counts()和布尔索引

先计算列B各值的出现次数,再筛选出仅出现一次的值,最后过滤DataFrame:

# 计算B列值的出现次数
b_counts = sample_df['B'].value_counts()
# 获取仅出现一次的B列值
unique_b_values = b_counts[b_counts == 1].index
# 过滤得到目标DataFrame
result_df = sample_df[sample_df['B'].isin(unique_b_values)]

解法二:利用groupby+filter(更简洁)

通过分组后过滤每组长度为1的行:

result_df = sample_df.groupby('B').filter(lambda group: len(group) == 1)

两种方法都能得到目标结果,可根据使用习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:07:44