Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在阵列中循环?_Python_Pandas - Fatal编程技术网

Python 如何在阵列中循环?

Python 如何在阵列中循环?,python,pandas,Python,Pandas,我读了几个关于熊猫数据帧的for循环的问题,但无法为我的案例解决 px=pd.read_sql() for i, row in px.iterrows(): if x == 1 : if px['first'] <= S1 : S1 = px['first']; if px['second'] > S2 : previous_value = last_value; la

我读了几个关于熊猫数据帧的for循环的问题,但无法为我的案例解决

px=pd.read_sql()

for i, row in px.iterrows():
    if x == 1 :
        if px['first'] <= S1 :
            S1 = px['first'];

        if px['second'] > S2 :
            previous_value = last_value;
            last_value = px['second'];
            x = 0;
    else :
.....

您正在从循环内部访问整个列px['first'],该循环一次只访问一个条目

要修复当前循环,只需将px['first']更改为row['first'],并将px['second']更改为row['second']就足够了


更好的办法是用等价的pandas表达式替换这种手动循环,这样会更快,可读性更好。如果您将完整的代码编辑发布到问题中,而不是作为注释!,我们可能会提供帮助。

我同意pandars表达式会快得多,但我怀疑是否有可能用pandas处理整个代码。我发布了我试图采用python代码的原始代码。听到这个消息太好了!查看您发布的代码,我看不到一种简单的方法——如果代码运行速度足够快,那么速度就不重要了:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().