计算 Python 中数组的元素

Counting elements of an array in Python

我一直在寻找练习的答案。 这个练习给了我们一个数组,其中的数字介于 -1 和 1 之间。 我们被要求计算信号数组改变符号的次数。 例如:你有这个数组: [0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2] 它改变标志 7 次 这是我编写的代码,应该得到它改变符号次数的“计数”。 由于某种原因,它不起作用,最后的计数等于 0,应该是 7。 你能帮我吗 ? 非常感谢。

--代码--

import numpy as np

def zeroCrossing(signal):

    j=0
    ls=len(signal)
    print(ls)
    count=0
    x=0
    y=0
    for j in range(0,ls):
        if signal[j]>0 and x==1:
            j=j+1
            y=0
        elif signal[j]>0 and x==0:
            count==count+1
            x=1
            j=j+1
        elif signal[j]<0 and y==1:
            j=j+1
            x=0
        elif signal[j]<0 and y==0:
            count==count+1
            y=1
            j=j+1
    
    return count

print(zeroCrossing(np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2])))

您没有修改 count 变量,因为您使用比较运算符而不是赋值。将 count==count+1 替换为 count=count+1 以修复它。

您只需按如下方式遍历数组即可实现您想要的效果:

sign_changes = 0
last_number = None
for n in my_array:
    if n < 0: # checks if n is negative
        if last_number != "negative": # checks if the last number was not negative
            sign_changes += 1
        last_number = "negative"
    else: # takes n as positive (including 0)
        if last_number != "positive": # checks if the last number was not positive
            sign_changes += 1
        last_number = "positive"

编辑:

此代码将在 OP 给出的示例数组中计数 7,正如 OP 所期望的那样,它将第一个数字计为“符号更改”。为避免这种情况(而不是计数 6 次符号更改),可以对代码进行小的调整。最简单的就是把last_number != "positive"last_number != "negative"条件分别改成last_number == "negative"last_number == "positive"

因为你总是把第一个数字算作 1 次,你可以试试这个 numpy 代码:

arr = np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2])
change_count = np.count_nonzero(np.diff(np.sign(arr))) + 1

Out[122]: 7