4

拥有一个包含多类目标变量的训练数据集category

train.groupby('category').size()

0     2220
1     4060
2      760
3     1480
4      220
5      440
6    23120
7     1960
8    64840

我想通过每个类的百分比(比如说 20%)从训练集中获取新的验证数据集,以避免在验证集中丢失类并破坏模型。所以基本上理想的输出将是 df 具有相同的结构和信息,如火车集,但参数如下:

0     444
1     812
2     152
3     296
4      44
5      88
6    4624
7     392
8   12968

是否有任何直接的方法可以在熊猫中解决它?

4

1 回答 1

3

Groupby 和 sample 应该为您做到这一点

df = pd.DataFrame({'category': np.random.choice(['a', 'b', 'c', 'd', 'e'], 100), 'val': np.random.randn(100)})

idx = df.groupby('category').apply(lambda x: x.sample(frac=0.2, random_state = 0)).index.get_level_values(1)

test = df.iloc[idx, :].reset_index(drop = True)
train = df.drop(idx).reset_index(drop = True)

编辑:您也可以使用 scikit 学习,

df = pd.DataFrame({'category': np.random.choice(['a', 'b', 'c', 'd', 'e'], 100), 'val': np.random.randn(100)})

X = df.iloc[:, :1].values
y = df.iloc[:, -1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = X)

X_train.shape, X_test.shape, y_train.shape, y_test.shape

((80, 1), (20, 1), (80,), (20,))
于 2018-11-26T23:18:50.883 回答