我在尝试通过对多数类进行随机欠采样来平衡数据框。虽然已经成功了,但我还想将从数据框中移除的(欠采样后的)数据保存到一个新的数据框中。我该如何实现这一点?
这是我用来对数据框进行欠采样的代码
from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(sampling_strategy=1)X_res, y_res = rus.fit_resample(X, y)df1 = pd.concat([X_res, y_res], axis=1)
回答:
RandomUnderSampler
有一个属性 sample_indices_
,表示保留的子样本的索引。所以这样应该可以:
dropped_ids = [i for i in range(X.shape[0]) if i not in rus.sample_indices_]X.iloc[dropped_ids] # 适用于数据框X[dropped_ids, :] # 适用于 numpy 数组