python - 如何在 Pandas 中删除固定数量的标记行?
问题描述
我有一个类不平衡的大熊猫数据框。所以我想将多数标签(我们称之为标签 1)下采样为固定数字。假设我有 1000 个标签 1,我希望数据框删除 500 个标签 1,我该怎么做?
解决方案
这是一个将减少 50% 的代码label == 1
。你可以决定如何计算你的n_to_drop
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1, 3, size=(10,2)),
columns=['Label', 'Other_Col'])
label_1 = df[df['Label'] == 1]
n_to_drop = label_1.shape[0]//2
index_to_drop = label_1.sample(n_to_drop).index
dropped_df = df.drop(index_to_drop)
print(df)
print(dropped_df)
Label Other_Col
0 1 2
1 1 2
2 2 1
3 1 1
4 2 1
5 1 2
6 2 1
7 2 2
8 1 1
9 2 2
Label Other_Col
0 1 2
2 2 1
3 1 1
4 2 1
6 2 1
7 2 2
8 1 1
9 2 2
推荐阅读
- reactjs - 如何将数组从 React 应用程序发送到 Flask 应用程序
- python - seaborn中带有子图的散点图
- bash - 存储别名的更好方法?
- ruby-on-rails - 获取并汇总所有关联的数据
- python - VBA 可以在我不指定路径的情况下识别 Python 位置吗?
- r - 使用 data.table 在多次熔化期间命名变量
- git - 为什么 git commit --author "name" 仍然无法提交错误 "empty ident name"
- sql - 将自由格式文本字段拆分为两个单独的列的问题
- google-apps-script - 如果错误看起来没问题,这个基本的重新运行功能吗
- python - 将 np.gradient 与日期时间一起使用