在数据框中混洗一组行的最佳方法是什么?对于模型的混洗训练集,需要这个。
例如,每10行作为一个单独的组进行混洗,或者有一些逻辑条件来创建单独的组并将它们作为一个组进行混洗。
发布于 2018-08-10 06:01:53
如果使用要分组的索引创建新列,则可以执行以下操作:
groups = [df.sample(frac=1) for _, df in df.groupby('index_to_group_on')]
return pandas.concat(groups)例如,如果您希望对每组10行进行混洗,则可以通过以下方式创建此索引:
df['group_of_ten'] = numpy.arange(len(df)/10)如果您正在尝试进行交叉验证,您可以查看scikit learn的train_test_split:http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
发布于 2018-08-10 06:57:36
也可能有其他方式,一种方式可能是使用sklearn的shuffle。您可以对要混洗的n行进行切片,并使用append将剩余的其他行转换为混洗后的行的结果。
from sklearn.utils import shuffle
# if df is the dataframe to then:
n = 10 # number of rows to shuffle
shuffled_df = shuffle(df[:n]).append(df[n:])发布于 2018-08-10 07:23:22
您可以做的是-创建一个标识组的列,然后按该列分组,然后对每个组进行随机洗牌。
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df['group_id'] = np.arange(df.shape[0]) // 10 # // is integer division in python3, won't work in python2
shuffled_groups = [v.drop(['group_id'], axis=1).sample(frac=1).reset_index(drop=True) for k, v in df.groupby('group_id')]https://stackoverflow.com/questions/51776744
复制相似问题