Check the missing integers from a range in Python

Viewed 116

Given a building infos dataframe as follows:

    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

I want to check if in the column floor, there are missing floors (except for floor 0, which is by default not existing).

Code:

set(df['floor'])

Out:

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

For example, for the dataset above (-2, -1, 1, 2, ..., 13), I want to return an indication floor 8, 10, 11 are missing in your dataset. Otherwise, just returns no missing floor in your dataset.

How could I do that in Pandas or Numpy? Thanks a lot for your help at advance.

1 Answers

Use np.setdiff1d for difference with range created np.arange and omitted 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
Related