Skip to main content
 首页 » 编程设计

python之如何通过保留至少两个非零列来对数据进行采样

2025年04月02日12fff_TT

我有一个基本上是 50K X9.5K 尺寸的 Pandas 数据框。我的数据集是二进制的,它只有 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:

这就是我想要实现的目标。

请您参考如下方法:

所以,对于非零,我猜你指的是那些只有 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) 

这是你要找的吗?