如何在pandas中查找dataframe内的唯一start与stop数值
pandas提取DataFrame中start、stop列唯一值的实现方法
以下方法默认你的数据集命名为df,且存储起止数值的列名为start和stop:
1. 单独提取单列唯一值
使用pandas内置的unique()方法即可直接获取单列的所有不重复值,返回结果为numpy数组格式:
- 提取start列唯一值:
df['start'].unique() - 提取stop列唯一值:
df['stop'].unique()
如果只需要统计唯一值的数量,用nunique()方法:
- 统计start列唯一值数量:
df['start'].nunique() - 统计stop列唯一值数量:
df['stop'].nunique()
如果需要排除空值后计算,可在方法前调用dropna(),示例:df['start'].dropna().unique()
2. 提取两列组合的唯一配对值
如果需要获取start和stop两列组合后的不重复记录,使用drop_duplicates()方法:
# 返回包含所有不重复(start, stop)配对的DataFrame df[['start', 'stop']].drop_duplicates() # 去重后重置索引,可添加ignore_index参数 df[['start', 'stop']].drop_duplicates(ignore_index=True)
示例效果
样例数据集:
import pandas as pd df = pd.DataFrame({ 'start': [1, 2, 2, 3, 3, 3], 'stop': [10, 20, 20, 30, 40, 40], 'other_col': ['a', 'b', 'c', 'd', 'e', 'f'] })
执行df['start'].unique()输出结果为:array([1, 2, 3])
执行df[['start','stop']].drop_duplicates()输出结果为:
| start | stop |
|---|---|
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
| 3 | 40 |
内容的提问来源于stack exchange,提问作者Alan
相关产品推荐
相关产品推荐

