在 pandas 数据框中,如何删除符合条件的行的随机子集?
换句话说,如果我有一个带有 Label
列的 Pandas 数据框,我想删除 50%(或其他百分比)的行,其中 Label == 1
,但保留所有其余部分:
Label A -> Label A
0 1 0 1
0 2 0 2
0 3 0 3
1 10 1 11
1 11 1 12
1 12
1 13
我很想知道执行此操作的最简单和最 pythonic/panda-ish 方法!
编辑:This question提供了部分答案,但它只讨论按索引删除行,而忽略行值。我仍然想知道如何仅从以特定方式标记的行中删除。
最佳答案
使用frac
参数
df.sample(frac=.5)
如果您在变量 n
中定义要转换的数量
n = .5
df.sample(frac=1 - n)
要包含条件,请使用 drop
df.drop(df.query('Label == 1').sample(frac=.5).index)
Label A
0 0 1
1 0 2
2 0 3
4 1 11
6 1 13
关于python - 来自 Pandas 数据框的 "Drop random rows",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934089/