【问题标题】:I am trying to take an 1D slice from 2D numpy array, but something goes wrong我正在尝试从 2D numpy 数组中获取 1D 切片,但出现问题
【发布时间】:2019-12-14 21:42:22
【问题描述】:

我正在尝试使用 3-sigma 规则从我的数据中过滤出明显的测量错误。 x 是测量点的 numpy 数组,y 是测量值的数组。为了从我的数据中删除错误的点,我压缩 x.tolist() 和 y.tolist(),然后过滤每个元组的第二个元素,然后我需要将我的 zip 转换回两个列表。我试图首先将我的元组列表转换为列表列表,然后将其转换为 numpy 2D 数组,然后取两个 1D 切片。看起来第一个切片是正确的,但随后输出如下:

x = np.array(list(map(list, list(filter(flt, list(zap))))))[:, 0]

IndexError: too many indices for array   

我不明白我做错了什么。代码如下:


x = np.array(readCol(0, l))
y = np.array(readCol(1, l))
n = len(y)

stdev = np.std(y)
mean = np.mean(y)

print("Stdev is: " + str(stdev))
print("Mean is: " + str(mean))

def flt(n):
    global mean
    global stdev
    global x
    if abs(n[1] - mean) < 3*stdev:
        return True
    else:
        print('flt function finds an error: ' + str(n[1]))
        return False


def filtration(N):
    print(Fore.RED + 'Filtration function launched')
    global y
    global x
    global stdev
    global mean
    zap = zip(x.tolist(), y.tolist())
    for i in range(N):
        print(Fore.RED + ' Filtration step number ' + str(i) + Style.RESET_ALL)
        y = np.array(list(map(list, list(filter(flt, list(zap))))))[:, 1]
        print(Back.GREEN + 'This is y: \n' + Style.RESET_ALL)
        print(y)
        x = np.array(list(map(list, list(filter(flt, list(zap))))))[:, 0]
        print(Back.GREEN + 'This is x: \n' + Style.RESET_ALL)
        print(x)
        print('filtration fuction main step')
        stdev = np.std(y)
        print('second step')
        mean = np.mean(y)
        print('third step')

【问题讨论】:

    标签: numpy python-3.7 numpy-ndarray numpy-slicing


    【解决方案1】:

    你有没有尝试过一步步测试问题线?

    x = np.array(list(map(list, list(filter(flt, list(zap))))))[:, 0]
    

    例如:

    temp = np.array(list(map(list, list(filter(flt, list(zap))))))
    print(temp.shape, temp.dtype)
    x = temp[:, 0]
    

    可能需要进一步分解,但由于[:,0] 是这一行中唯一的索引操作,我将从那里开始。

    如果不进一步研究代码和/或一些示例,我不会试图推测嵌套的lists 在做什么。

    错误听起来像temp 不是 2d,这与您的预期相反。这可能是因为 temp 是对象 dtype,并且由长度不同的列表组成。当人们从下载的数据库中制作数组时,这似乎是一个常见的问题。

    【讨论】:

    • 谢谢!我仍然不知道上面的代码有什么问题,但是在创建一个从中获取切片的临时数组之后,它工作正常。 temp = np.array(list(map(list, list(filter(flt, list(zap)))))) x = temp[:, 0] y = temp[:, 1]
    • P.S. : 温度是 2D
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2018-12-28
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多