我有一个类似下面的pandas DataFrame:
cli_id | X1 | X2 | X3 | ... | Xn | Y |
----------------------------------------
123 | 1 | A | XX | ... | 4 | 0.1 |
456 | 2 | B | XY | ... | 5 | 0.2 |
789 | 1 | B | XY | ... | 5 | 0.3 |
101 | 2 | A | XX | ... | 4 | 0.1 |
...
我有客户ID、几个分类属性和Y值,Y的值是从0到1以0.1为单位的事件概率。
我需要在每个组(即10个文件夹)中对大小为200的Y进行分层抽样
当进行训练/测试拆分时,我经常使用这种方法来进行分层抽样:
def stratifiedSplit(X,y,size):
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=size, random_state=0)
for train_index, test_index in sss:
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
return X_train, X_test, y_train, y_test
但是我不知道在这种情况下如何修改它。
df_test = df_stratified.droplevel(level=0)
。然后,您可以使用索引来获取训练集拆分:df_train = df[~df.index.isin(df_test.index)]
。 - NumesSanguisGroupBy
对象上的sample
才可用。 - Quickbeam2k1