【问题标题】:Spliting a numpy ndarray using slices使用切片拆分 numpy ndarray
【发布时间】:2014-01-28 11:13:51
【问题描述】:

Python 2.7.3 numpy 1.8.0

大家好, 我使用 numpy 几个月了,我需要一些基本的帮助。下面的代码应该可以工作,并且我需要帮助的部分被突出显示(#

import numpy as np

rng = np.random.RandomState(12345)

samples = np.array(np.arange(400).reshape(50, 8))
nSamples = samples.shape[0]
FOLDS = 15 

foldSize = nSamples / FOLDS

indices = np.arange(nSamples)
rng.shuffle(indices)

slices = [slice(i * foldSize ,
               (i + 1) * foldSize, 1) for i in xrange(FOLDS + 1)]

for i in xrange(len(slices)):
    y = samples[indices[slices[i]]]
    x = np.array([x for x in samples if x not in samples[slices[i]]]) # <<<<<<<
    #do some processing with x and y    

基本上随机对二维数组进行逐行切片,使用完整数组在切片位中进行处理和测试,然后对另一个切片重复进行,直到一切都完成(这称为交叉验证实验)。

我的问题是:有没有更好的方法来选择 ndarray 中的所有行,而不是切片?我错过了什么吗?如果 x 不在 samples[indices][0:3]] 中,[x for x in samples 如果 x not in samples[indices][0:3]] 的建议方法是什么?

提前致谢。

ps:屏蔽数组并不能解决我的问题。 ps1:我知道它已经在其他地方实现了,我只需要学习。

【问题讨论】:

    标签: python numpy slice


    【解决方案1】:

    您可以为要选择的行创建一个布尔数组,如下所示:

    indices_to_ignore = [1, 2, 3]
    mask = np.ones(samples.shape[:1], dtype=np.bool)
    mask[indices_to_ignore] = 0
    samples[mask].shape
    

    【讨论】:

    • 对不起,但掩蔽并不能解决我的问题,正如我在 PS 中所说的那样。还有其他解决方案吗?
    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2021-12-15
    • 2022-10-30
    • 2016-06-30
    • 2018-10-10
    • 1970-01-01
    相关资源
    最近更新 更多