【问题标题】:Check the missing integers from a range in Python在 Python 中检查一个范围内缺失的整数
【发布时间】:2021-01-07 08:12:15
【问题描述】:

给定如下的建筑信息数据框:

    id  floor     type
0    1     13   office
1    2     12   office
2    3      9   office
3    4      9   office
4    5      7   office
5    6      6   office
6    7      9   office
7    8      5   office
8    9      5   office
9   10      5   office
10  11      4   retail
11  12      3   retail
12  13      2   retail
13  14      1   retail
14  15     -1  parking
15  16     -2  parking
16  17     13   office

我想检查floor列中是否缺少楼层(0楼除外,默认情况下不存在)。

代码:

set(df['floor'])

输出:

{-2, -1, 1, 2, 3, 4, 5, 6, 7, 9, 12, 13}

例如,对于上面的数据集 (-2, -1, 1, 2, ..., 13),我想返回一个指示您的数据集中缺少第 8、10、11 层。否则,只返回您的数据集中没有丢失的楼层

我如何在 Pandas 或 Numpy 中做到这一点?非常感谢您提前提供的帮助。

【问题讨论】:

    标签: python-3.x pandas numpy dataframe range


    【解决方案1】:

    使用np.setdiff1d 与创建np.arange 并省略0 的范围不同:

    arr = np.arange(df['floor'].min(), df['floor'].max() + 1)
    arr = arr[arr != 0]
    
    out = np.setdiff1d(arr, df['floor'])
    
    out = ('no missing floor in your dataset' 
           if len(out) == 0 
           else f'floor(s) {", ".join(out.astype(str))} are missing in your dataset')
    print (out)
    floor(s) 8, 10, 11 are missing in your dataset
    

    【讨论】:

    • 谢谢,如果我想自动从列floor获取范围值?
    • @ahbon 那是np.arange 不是np.arrange
    • 是的,我注意到了。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多