我需要从数据框中获取一个样本,但是我还需要不属于该样本的值。例如:
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
首先需要使用,然后boolean indexing
与eq
或一起使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句