通过使用熊猫中groupby()的百分比从Train set获取验证集

时间:2018-11-26 23:13:18

标签: python pandas group-by cross-validation train-test-split

拥有包含多类目标变量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

有没有简单的方法可以解决大熊猫问题?

1 个答案:

答案 0 :(得分: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,))