首页 > 解决方案 > 如何在 Pandas 中删除固定数量的标记行?

问题描述

我有一个类不平衡的大熊猫数据框。所以我想将多数标签(我们称之为标签 1)下采样为固定数字。假设我有 1000 个标签 1,我希望数据框删除 500 个标签 1,我该怎么做?

标签: pythonpandasdataframe

解决方案


这是一个将减少 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

推荐阅读