我有一个熊猫数据框,基本上是50K X9.5K尺寸。我的数据集是二进制的,它只有1和0。并且有很多零。
可以将其视为用户项购买数据,如果用户购买了项则为1,否则为0。用户为行,项目为列。
353 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
354 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
355 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
356 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
357 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
我想分为训练,验证和测试集。但是,这不会只是正常的按行拆分。
我想要的是,对于每个验证和测试集,我希望保留原始数据中的2-4列(非零)。
所以基本上,如果我的原始数据为每个用户有9.5K列,那么我首先仅保留1500左右的列。然后,我将采样数据吐入训练并进行测试,方法是在训练中保留1495-1498列,在测试/验证中保留2-5列。测试中的列仅是非零的列。培训可以兼得。
我还想保持项目名称/索引与测试/验证中保留的名称/索引相对应
我不想运行循环以检查每个单元格值并将其放在下一张表中。
任何的想法?
编辑1:
所以这就是我想要达到的目标。
最佳答案
因此,我猜您的意思是非零的那些列中只有一列。那很容易做到。最好的方法可能是使用sum,如下所示:
sums = df.sum(axis=1) # to sum along columns. You will have a Series with column names as indices, and column sums as values.
non_zero_cols = sums[sums = len(df)].index # this will have only column names with non-zero records
# Now to split the data into training and testing
test_cols = numpy.random.choice(non_zero_cols, 2, replace=False) # or 5, just randomly selecting columns.
test_data = df[test_cols]
train_data = df.drop(test_cols)
那是您要找的东西吗?
关于python - 如何通过至少保留两个非零列来采样数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38381345/