根据条件从数据框中随机删除行

时间:2017-01-28 16:40:08

标签: python pandas

给定一个特定列中具有数值的数据框,我想随机删除该特定列中的值位于特定范围内的一定百分比的行。

例如,给出以下数据帧:

df = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9,10]})
df
   col1
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10

col1低于6的行中的2/5应随机删除。

最简洁的方法是什么?

1 个答案:

答案 0 :(得分:8)

使用sample + drop

df.drop(df.query('col1 < 6').sample(frac=.4).index)

   col1
1     2
3     4
4     5
5     6
6     7
7     8
8     9
9    10

对于范围

df.drop(df.query('2 < col1 < 8').sample(frac=.4).index)

   col1
0     1
1     2
3     4
4     5
5     6
7     8
8     9
9    10
相关问题