关于你的问题,
有没有办法从另一个数据中减去一个数据?
您可以简单地从主 DataFrame 中删除属于 Test 的索引以获取您的 Train。试试这个 -
train = df.drop(test.index, axis=0)
#Where df is the main dataset from which test data has been sampled.
#train, test, df are all pd.DataFrames
但是,如果您正在为机器学习问题准备数据,我会推荐一些更好的方法,如我的答案的下一部分所述。
1。使用 Sklearn API(推荐)
您可以尝试使用sklearn.model_selection.train_test_split api 来为您节省大量进行此类训练测试拆分的时间。
from sklearn.model_selection import train_test_split
df = pd.DataFrame(np.random.random((100,10)))
train, test = train_test_split(df, test_size=0.2)
train.shape, test.shape
((80, 10), (20, 10))
2。使用 pandas 方法
另一种方法是从 df 中抽取 20% 的数据,然后过滤其余数据以进行训练。
test = df.sample(frac=0.2)
train = df.loc[~df.index.isin(test.index)]
train.shape, test.shape
((80, 10), (20, 10))
3。从索引列表开始
假设您已经有一个索引列表 (test_idx),正如您在问题中提到的那样。在这种情况下,您仍然可以使用 pandas 方法来执行此操作,而无需任何 for 循环或 pop()
test_idx = np.random.choice(range(100), 20, replace=False) #approx 20% random indexes
test = df.loc[df.index.isin(test_idx)]
train = df.loc[~df.index.isin(test_idx)]
train.shape, test.shape
((80, 10), (20, 10))