我有一个像这样的数据框:
Col1 Col2
a1 1
a2 1
b1 2
b2 2
b3 2
b4 2
如果 Col2 = 2,我想随机删除 2 行。示例输出:
Col1 Col2
a1 1
a2 1
b1 2
b4 2
执行此操作的最佳方法是什么?谢谢:)
最佳答案
这可能不是最好的解决方案,但它确实有效
首先获取相对于条件Col2 == 2
的索引
index = df.index[df.Col2 == 2].tolist()
然后“随机”选择要删除的两行
import random
idx = random.sample(index, 2)
df.drop(index=idx)
关于Python数据框: Randomly delete rows with initial condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56186952/