首页 文章

如果值出现一次,则更新pandas列以使用np.nan替换值,然后重置另一个值occus

提问于
浏览
-1

Headers 非常令人困惑,所以让我解释一下 . 我有一个熊猫专栏:

x   | desired x
1.5 | 1
1   | 1
1   | 1         
1   | 1
1   | 1
0   | 0
0   | 0
0   | 0
0   | 0
1   | 0
0   | 0
-1.5|-1
-1  |-1
-1  |-1
-1  |-1
0   | 0  
0   | 0
0   | 0
0   | 0
-1  | 0
0   | 0
0   | 0
1.5 | 1

...

目前,我已经使用itertuples解决了这个问题:

currval = np.nan
for idx in df.itertuples():
    if idx[33] == 1.5: 
        currval = 1
    elif idx[33] == -1.5:
        currval = -1
    elif idx[32] <> "":
        currval = np.nan
    else: 
        next
    df.loc[idx.Index,'refPos2'] = currval

然而,这段代码太慢了,并且想知道是否有人有关于如何对此进行矢量化的想法 .

谢谢!

1 回答

  • 0

    我从评论中理解的问题陈述,这里是解决方案:

    for index, item in enumerate(a): ## a is your list [-1.5,1,1,0,1,1.5]
        if item == 1.5:
           a[index] = 1
        elif item == -1.5:
           a[index] = -1
        elif a[index] == 0:
            a[index] = 0
        elif a[index] == 1 and a[index-1] ==0:
            a[index] = 0
        else:
            a[index] =1
    

相关问题