我正在做一个机器学习计算,它有两个数据框——一个用于因子,另一个用于目标值。我必须分成训练和测试部分。在我看来,我已经找到了方法,但我正在寻找更优雅的解决方案。这是我的代码:
import pandas as pd
import numpy as np
import random
df_source = pd.DataFrame(np.random.randn(5,2),index = range(0,10,2), columns=list('AB'))
df_target = pd.DataFrame(np.random.randn(5,2),index = range(0,10,2), columns=list('CD'))
rows = np.asarray(random.sample(range(0, len(df_source)), 2))
df_source_train = df_source.iloc[rows]
df_source_test = df_source[~df_source.index.isin(df_source_train.index)]
df_target_train = df_target.iloc[rows]
df_target_test = df_target[~df_target.index.isin(df_target_train.index)]
print('rows')
print(rows)
print('source')
print(df_source)
print('source train')
print(df_source_train)
print('source_test')
print(df_source_test)
---- 编辑 - unutbu 的解决方案 (midified) ---
np.random.seed(2013)
percentile = .6
rows = np.random.binomial(1, percentile, size=len(df_source)).astype(bool)
df_source_train = df_source[rows]
df_source_test = df_source[~rows]
df_target_train = df_target[rows]
df_target_test = df_target[~rows]