找出一系列整数中跳过的值

2024-03-28 23:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框中有一列是不包含重复的客户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

2条回答

以下面的dataframe为例:

In [2454]: df
Out[2454]: 
   customer_id
0            1
1            2
2            3
3            4
4            5
5            8
6            9
7           10

您可以使用^{}

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]

假设dtype是int(看起来是这样),我们可以在这里从numpy使用^{}

c_id = df['customer_id']
missing_ids = np.setdiff1d(np.arange(c_id.min(), c_id.max()+1), c_id)

相关问题 更多 >