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

标签 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。

最简洁的方法是什么?

最佳答案

使用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

关于python - 根据条件从数据框中随机删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912204/

相关文章:

python - pandas - 获取每个多索引级别标签行的一小部分

python - 这个条件运算符有什么作用?

python - Plotly 的 treemap 和 sunburst 显示错误的大小

python - 按前 N% 对 pandas 数据进行分箱

python - 我无法制作我理想的 DataFrame

python - 提取括号之间的文本并为每个文本位创建行

python - NumPy 的 : Check array for string data type

python - 与使用 Python/Gradle 转义字符相关的跨平台问题

python - 在 Pandas 的前几行中获取第一个非零值

python - 将多个文件中的所有列合并为一个(在一行中!)