【问题标题】:Find out skipped values in a Series of integers找出一系列整数中的跳过值
【发布时间】:2021-04-04 07:39:24
【问题描述】:
我的数据框中有一列是不包含重复的客户 ID。 id 系列从整数 1 开始,到 4003 结束。如以下输出所示,有 4 个 id 编号被跳过。我想要一些帮助来找出它们是什么。提前致谢!
df['customer_id'].describe()
Out[150]:
count 3999
unique 3999
top 4003
freq 1
Name: customer_id, dtype: int64
【问题讨论】:
标签:
python
pandas
dataframe
indexing
【解决方案1】:
下面以dataframe为例:
In [2454]: df
Out[2454]:
customer_id
0 1
1 2
2 3
3 4
4 5
5 8
6 9
7 10
你可以使用set symmetric difference:
In [2437]: a = df['customer_id'].tolist()
In [2431]: b = [x for x in range(a[0], a[-1] + 1)]
In [2438]: missing_vals = list(set(a) ^ set(b))
In [2439]: missing_vals
Out[2439]: [6, 7]
【解决方案2】:
假设 dtype 是 int(似乎是这种情况),看起来我们可以在这里从 numpy 使用setdiff1d:
c_id = df['customer_id']
missing_ids = np.setdiff1d(np.arange(c_id.min(), c_id.max()+1), c_id)