给定一个特定列中具有数值的数据帧,我想随机删除该特定列中的值位于特定范围内的一定百分比的行.
例如,给定以下数据帧:
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
Run Code Online (Sandbox Code Playgroud)
col1低于6的2/5行应随机删除.
什么是最简洁的方法呢?
piR*_*red 12
用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
Run Code Online (Sandbox Code Playgroud)
适用范围
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2162 次 |
| 最近记录: |