如何在 Python 中查找不属于样本的值?

How to find values that don't belong to sample in Python?

我需要从数据框中提取样本,但我还需要不属于该样本的值。例如:

data = [[1,2,3,55], [1,2,34,5], [13,2,3,5], [1,2,32,5], [1,2,22,5]]
df = DataFrame(data=data, index=[0, 0, 1, 1, 1], columns=['A', 'B', 'C', 'D'])

输出:

In[97]: df.sample(3)
Out[97]: 

    A  B   C   D
1   1  2  32   5
0   1  2   3  55
1  13  2   3   5

如何获取剩余的 2 个样本?有什么基本的方法可以做到这一点吗?

重复索引是有问题的,所以需要reset_index firstly, then use boolean indexing with eq or isin:

df = df.reset_index()
sam = df.sample(3)
print (sam)
   index  A  B   C   D
0      0  1  2   3  55
1      0  1  2  34   5
3      1  1  2  32   5

print ((df.eq(sam, 1)).all(1))
0     True
1     True
2    False
3     True
4    False
dtype: bool

print ((df.isin(sam)).all(1))
0     True
1     True
2    False
3     True
4    False
dtype: bool

print (df[~(df.isin(sam)).all(1)])
   index   A  B   C  D
2      1  13  2   3  5
4      1   1  2  22  5

最后重新分配索引:

print (sam.set_index('index').rename_axis(None))
   A  B   C   D
0  1  2   3  55
0  1  2  34   5
1  1  2  32   5

print (df[~(df.isin(sam)).all(1)].set_index('index').rename_axis(None))
    A  B   C  D
1  13  2   3  5
1   1  2  22  5