自条件列

2024-04-20 01:59:00 发布

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

我试图在pandas中创建一个列,该列与其他列一起以它以前的值为条件。你知道吗

import pandas as pd
import numpy as np
a = np.random.standard_normal(100)
A = pd.DataFrame(a)
A['Out'] = 0
A['Out2'] = 0
for t in range(1,A.shape[0]):
    if (A[0][t] > 1) & (A['Out'][t-1]==0):
        A['Out'][t] = 1
    elif (A[0][t] < -1) & (A['Out'][t-1]==0):
        A['Out'][t] = -1
    elif ((A[0][t] > 0) & (A['Out'][t-1]==-1)) | ((A[0][t] < 0) & (A['Out'][t-1]==1)):
        A['Out'][t] = 0
    else:
        A['Out'][t] = A['Out'][t-1] 
A['Out2'] = np.where((A.index== 0),0
        ,np.where((A[0] > 1) & (A['Out2'].shift()==0), 1
        ,np.where((A[0] < -1) & (A['Out2'].shift()==0), -1
        ,np.where(((A[0] > 0) & (A['Out2'].shift()==-1)) | ((A[0] < 0) & (A['Out2'].shift()==1)), 0
        ,A['Out2'].shift()))))

列A['Out2']尝试以矢量形式复制['Out'],但不读取以前的值。列A['Out']在循环中编译花费的时间太长。有人能帮我一个更快,矢量化的方法来创建这个专栏吗?你知道吗


Tags: importnumpypandasshiftasnprandomout
1条回答
网友
1楼 · 发布于 2024-04-20 01:59:00

您可以创建一个函数,然后使用apply。要访问以前的数据,可以使用变量存储该值。希望下面的代码有帮助。你知道吗

import pandas as pd
import numpy as np
a = np.random.standard_normal(100)
A = pd.DataFrame(a)
state = 0
def get_val(A,prev_state):
    global state
    if (A > 1) & (prev_state==0):
        state = 1
    elif (A < -1) & (prev_state==0):
        state = -1
    elif ((A > 0) & (prev_state==-1)) | ((A < 0) & (prev_state==1)):
        state = 0     
    return state

A['Out'] = A[0].apply(lambda x: get_val(x,state))

输出:

           0  Out 
0  1.366864    1     
1  0.887763    1     
2 -0.663636    0     
3 -1.824950   -1     
4  0.459663    0    
5 -1.325129   -1     
6  1.587188    0    
7 -0.148159    0     
8  0.578862    0     
9  0.758460    0     

如果你用%%timeit

100 loops, best of 3: 2.16 ms per loop 

相关问题 更多 >