熊猫数据框,使用.apply(lambda x :...)但取决于最后一个x值

2024-09-27 19:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想有一个更快的方法来做下面的一列数据帧。 现在我只能在for循环中这样做,而且速度很慢。但在使用lambda时,我不能依赖于last(x)

for i in range(len(Zscore_list)):
    if len(Pos_list) != 0:
        if Pos_list[i-1] == 1:
            if Zscore_list[i] < -Thre2:
                Pos_list.append(1)
            else:
                Pos_list.append(0)
        elif Pos_list[i-1] == -1:
            if Zscore_list[i] > Thre2:
                Pos_list.append(-1)
            else:
                Pos_list.append(0)
        elif Pos_list[i-1] == 0:
            if Zscore_list[i] > Thre:
                Pos_list.append(-1)
            elif Zscore_list[i] < -Thre:
                Pos_list.append(1)
            else:
                Pos_list.append(0) 
    else:
        if Zscore_list[i] > Thre:
             Pos_list.append(-1)
        elif Zscore_list[i] < -Thre:
            Pos_list.append(1)
        else:
            Pos_list.append(0)

Tags: 数据方法lambdaposforlenifelse
1条回答
网友
1楼 · 发布于 2024-09-27 19:18:32

可能有更多的方法可以做到这一点,但这里有一个可能的解决方案:

zlist = [1,5,9,10,9,5,3,1,0,-3,-4,-10]

df = pd.DataFrame(zlist_series, columns = ["Z"])
df["Change_Point"] = df["Z"].apply(lambda x: int(abs(x) >= 10 or x == 0)) 
df["Change_Point_Is_Odd"] = df.Change_Point.cumsum().apply(lambda x: int(bool(x%2)))
df["Sign_Of_Change"] = df.Z.apply(lambda x: math.copysign(int(bool(abs(x))), x)) 
df["P"] = df.Change_Point_Is_Odd * df.Sign_Of_Change 
df.P = df.P.astype('int')

''' This is the output
     Z  Change_Point  Sign_Of_Change  Change_Point_Is_Odd  P
0    1             0             1.0                    0  0
1    5             0             1.0                    0  0
2    9             0             1.0                    0  0
3   10             1             1.0                    1  1
4    9             0             1.0                    1  1
5    5             0             1.0                    1  1
6    3             0             1.0                    1  1
7    1             0             1.0                    1  1
8    0             1             0.0                    0  0
9   -3             0            -1.0                    0  0
10  -4             0            -1.0                    0  0
11 -10             1            -1.0                    1 -1
'''

相关问题 更多 >

    热门问题